// supabase/functions/send-campaign-email/index.ts
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { Resend } from "npm:resend@2.0.0";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.49.1";

const resend = new Resend(Deno.env.get("RESEND_API_KEY"));

const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
};

interface SendEmailRequest {
    contact_id: string;
    subject: string;
    html_body: string;
    text_body?: string;
    from_name?: string;
    from_email?: string;
    campaign_id?: string;
}

function json(status: number, body: Record<string, unknown>) {
    return new Response(JSON.stringify(body), {
        status,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
}

function renderTemplate(input: string, vars: Record<string, string>) {
    let out = input;
    for (const [k, v] of Object.entries(vars)) {
        out = out.replaceAll(`{{${k}}}`, v ?? "");
    }
    return out;
}

serve(async (req: Request): Promise<Response> => {
    if (req.method === "OPTIONS") return new Response(null, { headers: corsHeaders });

    try {
        const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
        const supabaseServiceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
        const supabase = createClient(supabaseUrl, supabaseServiceKey, {
            auth: { persistSession: false },
        });

        // Require auth (so people can’t use your function to send arbitrary emails)
        const authHeader = req.headers.get("Authorization");
        if (!authHeader) return json(401, { error: "Missing Authorization header" });

        const token = authHeader.replace("Bearer ", "");
        const { data: userRes, error: userErr } = await supabase.auth.getUser(token);
        if (userErr || !userRes?.user) return json(401, { error: "Invalid token" });

        const {
            contact_id,
            subject,
            html_body,
            text_body,
            from_name,
            from_email,
            campaign_id,
        }: SendEmailRequest = await req.json();

        if (!contact_id || !subject || !html_body) {
            return json(400, { error: "contact_id, subject, html_body are required" });
        }

        // Fetch contact
        const { data: contact, error: contactError } = await supabase
            .from("contacts")
            .select("id, email, first_name, last_name, company")
            .eq("id", contact_id)
            .maybeSingle();

        if (contactError || !contact) return json(404, { error: "Contact not found" });

        // Suppression check
        const { data: suppressed } = await supabase
            .from("suppression_list")
            .select("id, reason")
            .eq("email", contact.email)
            .maybeSingle();

        if (suppressed) {
            return json(200, { status: "skipped", reason: "suppressed" });
        }

        // Sender
        const { data: business } = await supabase.from("business").select("name, email").limit(1).maybeSingle();

        const senderName = from_name || business?.name || Deno.env.get("DEFAULT_FROM_NAME") || "Your Business";
        const senderEmail = from_email || business?.email || Deno.env.get("DEFAULT_FROM_EMAIL") || "onboarding@resend.dev";

        const vars = {
            first_name: contact.first_name || "",
            last_name: contact.last_name || "",
            email: contact.email || "",
            company: (contact as any).company || "",
        };

        const renderedSubject = renderTemplate(subject, vars);
        const renderedHtml = renderTemplate(html_body, vars);
        const renderedText = text_body ? renderTemplate(text_body, vars) : undefined;

        const unsubscribeUrl =
            `${supabaseUrl}/functions/v1/handle-unsubscribe` +
            `?email=${encodeURIComponent(contact.email)}` +
            (campaign_id ? `&campaign_id=${encodeURIComponent(campaign_id)}` : "");

        const htmlWithUnsubscribe =
            renderedHtml +
            `
<div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; text-align: center; font-size: 12px; color: #666;">
  <p>You received this email because you are subscribed to our mailing list.</p>
  <p><a href="${unsubscribeUrl}" style="color: #666;">Unsubscribe</a></p>
</div>
`;

        const emailResponse = await resend.emails.send({
            from: `${senderName} <${senderEmail}>`,
            to: [contact.email],
            subject: renderedSubject,
            html: htmlWithUnsubscribe,
            text: renderedText,
        });

        if (emailResponse.error) {
            await supabase.from("email_logs").insert({
                campaign_id,
                contact_id: contact.id,
                recipient_email: contact.email,
                subject: renderedSubject,
                status: "failed",
                error_message: emailResponse.error.message,
            });

            return json(500, { error: emailResponse.error.message });
        }

        await supabase.from("email_logs").insert({
            campaign_id,
            contact_id: contact.id,
            recipient_email: contact.email,
            subject: renderedSubject,
            status: "sent",
            resend_id: emailResponse.data?.id,
        });

        // Optional activity log
        await supabase.from("activities").insert({
            user_id: userRes.user.id,
            contact_id: contact.id,
            type: "email",
            direction: "outbound",
            category: "user",
            status: "logged",
            subject: renderedSubject,
            body_preview: (renderedText || renderedHtml.replace(/<[^>]*>/g, "")).substring(0, 200),
        });

        return json(200, { status: "sent", resend_id: emailResponse.data?.id });
    } catch (error: any) {
        return json(500, { error: error?.message || "Unknown error" });
    }
});