import { NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { sendCampaignEmail } from "@/lib/email-service";

/**
 * Cron: /api/cron/send-scheduled
 * Runs daily at 09:00 (declared in vercel.json).
 * Finds all campaigns with status='scheduled' and scheduled_at <= now(),
 * sends each one to all opted-in contacts for that brand, then marks
 * the campaign as 'sent'.
 *
 * Auth: Bearer token via CRON_SECRET header.
 */
export async function GET(request: Request) {
  const authHeader = request.headers.get("authorization") ?? "";
  const expected = `Bearer ${process.env.CRON_SECRET ?? ""}`;
  if (!expected || authHeader !== expected) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    // 1. Find campaigns due to be sent
    const { rows: campaigns } = await pool.query<{
      id: string;
      brand_id: string;
      name: string;
      subject: string | null;
      body_html: string | null;
      brand_name: string | null;
    }>(
      `SELECT id, brand_id, name, subject, body_html, brand_name
       FROM communication_campaigns
       WHERE status = 'scheduled'
         AND scheduled_at IS NOT NULL
         AND scheduled_at <= now()
       ORDER BY scheduled_at ASC`
    );

    if (campaigns.length === 0) {
      return NextResponse.json({ success: true, timestamp: new Date().toISOString(), results: [] });
    }

    const results: Array<{ campaignId: string; name: string; sent: number; errors: number }> = [];

    for (const campaign of campaigns) {
      if (!campaign.body_html) {
        await pool.query(
          `UPDATE communication_campaigns SET status = 'sent', sent_at = now() WHERE id = $1`,
          [campaign.id]
        );
        results.push({ campaignId: campaign.id, name: campaign.name, sent: 0, errors: 0 });
        continue;
      }

      // 2. Find opted-in contacts for this brand
      const { rows: contacts } = await pool.query<{ id: string; email: string | null; full_name: string | null }>(
        `SELECT id, email, full_name
         FROM communication_contacts
         WHERE brand_id = $1
           AND email_opt_in = true
           AND email IS NOT NULL
           AND unsubscribed_at IS NULL`,
        [campaign.brand_id]
      );

      let sent = 0;
      let errors = 0;

      for (const contact of contacts) {
        if (!contact.email) continue;
        const result = await sendCampaignEmail({
          to: contact.email,
          subject: campaign.subject ?? campaign.name,
          html: campaign.body_html,
        });
        if (result.ok) sent++;
        else {
          errors++;
          console.error(
            `[cron/send-scheduled] campaign ${campaign.id} contact ${contact.email}:`,
            result.error,
          );
        }
      }

      // 3. Mark campaign as sent
      await pool.query(
        `UPDATE communication_campaigns
         SET status = 'sent', sent_at = now(), recipient_count = $2
         WHERE id = $1`,
        [campaign.id, sent]
      );

      results.push({ campaignId: campaign.id, name: campaign.name, sent, errors });
    }

    return NextResponse.json({ success: true, timestamp: new Date().toISOString(), results });
  } catch (err) {
    console.error("[cron/send-scheduled] Error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}