import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";
import { randomBytes } from "crypto";
import { Resend } from "resend";

const RESEND_API_KEY = process.env.RESEND_API_KEY;
const EMAIL_FROM    = process.env.EMAIL_FROM || "Tia <tia@manohargupta.com>";
const APP_URL       = process.env.NEXT_PUBLIC_APP_URL || "https://tia.manohargupta.com";

// POST — invite a person by email (admin only)
export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const auth = await requireFamily();
    if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

    const familyId = auth.session!.familyId!;
    const { id: circleId } = await params;

    // Only admins can invite
    const rows = await sql.unsafe(
      `SELECT role FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
      [circleId, familyId]
    );
    if (!rows[0] || rows[0].role !== "admin") {
      return NextResponse.json({ error: "Only circle admins can invite members" }, { status: 403 });
    }

    const body = await req.json();
    const email: string = (body.email ?? "").trim().toLowerCase();
    if (!email || !email.includes("@")) {
      return NextResponse.json({ error: "Valid email address required" }, { status: 400 });
    }

    // Fetch circle info for the email
    const [circle] = await sql.unsafe(
      `SELECT name FROM circles WHERE id = $1`,
      [circleId]
    );
    const [inviterFamily] = await sql.unsafe(
      `SELECT name FROM families WHERE id = $1`,
      [familyId]
    );

    // Look up if the email belongs to an existing user → find their family
    const userRows = await sql.unsafe(
      `SELECT u.id as user_id, fm.family_id
       FROM users u
       LEFT JOIN family_members fm ON fm.user_id = u.id
       WHERE u.email = $1
       LIMIT 1`,
      [email]
    );
    const invitedFamilyId: string | null = userRows[0]?.family_id ?? null;

    // Don't invite someone already in the circle
    if (invitedFamilyId) {
      const already = await sql.unsafe(
        `SELECT 1 FROM circle_members WHERE circle_id = $1 AND family_id = $2`,
        [circleId, invitedFamilyId]
      );
      if (already.length > 0) {
        return NextResponse.json({ error: "This family is already a member of the circle" }, { status: 409 });
      }

      // Check for an existing pending invite to the same family
      const pending = await sql.unsafe(
        `SELECT 1 FROM circle_invites
         WHERE circle_id = $1 AND invited_family_id = $2 AND consumed_at IS NULL AND expires_at > now()`,
        [circleId, invitedFamilyId]
      );
      if (pending.length > 0) {
        return NextResponse.json({ error: "An invite is already pending for this person" }, { status: 409 });
      }
    }

    const token     = randomBytes(32).toString("hex");
    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();
    const joinUrl   = `${APP_URL}/circle/join/${token}`;

    await sql.unsafe(
      `INSERT INTO circle_invites (circle_id, token, created_by, expires_at, invited_email, invited_family_id)
       VALUES ($1, $2, $3, $4, $5, $6)`,
      [circleId, token, familyId, expiresAt, email, invitedFamilyId]
    );

    if (invitedFamilyId) {
      // Existing user — they'll see the pending invite on their circles page
      return NextResponse.json({ success: true, type: "in_app" });
    }

    // Non-registered user — send email via Resend
    if (RESEND_API_KEY) {
      try {
        const resend = new Resend(RESEND_API_KEY);
        await resend.emails.send({
          from: EMAIL_FROM,
          to:   email,
          subject: `${inviterFamily?.name ?? "Someone"} invited you to join ${circle?.name ?? "a circle"} on Tia`,
          html: `
            <div style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px">
              <h2 style="margin-bottom:8px">You're invited! 👨‍👩‍👧‍👦</h2>
              <p style="color:#374151">
                <strong>${inviterFamily?.name ?? "A family"}</strong> has invited you to join
                their circle <strong>"${circle?.name ?? "a circle"}"</strong> on Tia — a baby tracking app for families.
              </p>
              <p style="color:#6b7280;font-size:14px">
                Create a free account to join them and start sharing milestones, memories, and updates.
              </p>
              <a href="${APP_URL}/login?next=/circle/join/${token}"
                style="display:inline-block;background:#fb7185;color:white;padding:12px 24px;
                       text-decoration:none;border-radius:10px;margin:16px 0;font-weight:600">
                Create Account &amp; Join Circle
              </a>
              <p style="color:#6b7280;font-size:13px">
                Already have an account?
                <a href="${joinUrl}" style="color:#fb7185">Click here to join directly</a>.
              </p>
              <p style="color:#9ca3af;font-size:12px;margin-top:24px">
                This invite expires in 7 days. If you didn't expect this, you can ignore this email.
              </p>
            </div>
          `,
        });
      } catch (emailErr) {
        console.error("[CIRCLE-INVITE-EMAIL-FAILED]", emailErr);
      }
    }

    return NextResponse.json({ success: true, type: "email_sent" });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
