import { BadRequestException, Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import { PrismaService } from '../common/prisma.service';
import { getMerchant } from '../common/core';

@Controller('admin')
export class MarketingController {
  constructor(private prisma: PrismaService) {}

  // --- Digital Assets (PRD 4.2) — merchant uploads, affiliates use ---
  @Get('assets')
  async assets() {
    const m = await getMerchant(this.prisma);
    const list = await this.prisma.asset.findMany({ where: { merchantId: m.id }, orderBy: { createdAt: 'desc' } });
    return list.map((a) => ({
      id: a.id,
      type: a.type,
      title: a.title,
      url: a.url,
      category: a.category,
      date: a.createdAt.toISOString().slice(0, 10),
    }));
  }

  @Post('assets')
  async createAsset(@Body() body: Record<string, any>) {
    const m = await getMerchant(this.prisma);
    if (!body.title?.trim() || !body.url?.trim()) throw new BadRequestException('Title and URL are required');
    const a = await this.prisma.asset.create({
      data: { merchantId: m.id, type: (body.type as any) || 'IMAGE', title: body.title, url: body.url, category: body.category || null },
    });
    return { ok: true, id: a.id };
  }

  @Delete('assets/:id')
  async deleteAsset(@Param('id') id: string) {
    await this.prisma.asset.delete({ where: { id } });
    return { ok: true };
  }

  // --- Communications (PRD 4.9) ---
  @Get('emails')
  async emails() {
    const m = await getMerchant(this.prisma);
    const logs = await this.prisma.emailLog.findMany({ where: { merchantId: m.id }, orderBy: { sentAt: 'desc' }, take: 100 });
    return logs.map((l) => ({
      id: l.id,
      to: l.toEmail,
      type: l.type,
      subject: l.subject,
      date: l.sentAt.toISOString().slice(0, 16).replace('T', ' '),
      status: l.status,
    }));
  }

  @Post('emails/bulk')
  async bulkEmail(@Body() body: { subject?: string; audience?: string }) {
    if (!body.subject?.trim()) return { ok: false, message: 'Subject is required' };
    const m = await getMerchant(this.prisma);
    const where: any = { merchantId: m.id };
    if (body.audience && body.audience !== 'all') where.status = body.audience;
    const affs = await this.prisma.affiliate.findMany({ where, select: { email: true } });
    if (affs.length)
      await this.prisma.emailLog.createMany({
        data: affs.map((a) => ({ merchantId: m.id, toEmail: a.email, type: 'bulk_broadcast', subject: body.subject! })),
      });
    return { ok: true, sent: affs.length };
  }
}
