import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";
import { randomBytes } from "crypto";
import { sendFamilyInviteEmail } from "@/lib/email";
import { checkMemberLimit } from "@/lib/quota";

// GET - list invites for a family
export async function GET(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const invites = await sql.unsafe(
      `SELECT id, email, role, expires_at as "expiresAt", created_at as "createdAt"
       FROM family_invites
       WHERE family_id = $1 AND expires_at > NOW()
       ORDER BY created_at DESC`,
      [auth.session!.familyId]
    );
    return NextResponse.json({ invites: invites || [] });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// POST - create invite
export async function POST(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { email, role, displayName } = body;

    if (!email) {
      return NextResponse.json({ error: "email required" }, { status: 400 });
    }

    // Member limit gate — COUNT(family_members) is source of truth.
    // Freeze rule: paid → free downgrade leaves existing members intact;
    // only new invites are blocked until family is under limit or upgrades.
    const limitCheck = await checkMemberLimit(auth.session!.familyId!);
    if (!limitCheck.allowed) {
      return NextResponse.json(
        {
          error: limitCheck.message,
          reason: limitCheck.reason,
          currentCount: limitCheck.currentCount,
          limit: limitCheck.limit,
        },
        { status: 403 }
      );
    }

    const token = randomBytes(32).toString("hex");
    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + 7); // 7 days

    const [invite] = await sql.unsafe(
      `INSERT INTO family_invites (family_id, email, role, token, expires_at)
       VALUES ($1, $2, $3, $4, $5)
       RETURNING id, email, role, expires_at as "expiresAt"`,
      [auth.session!.familyId, email, role || "caregiver", token, expiresAt.toISOString()]
    );

    // Send invite email — capture result so caller can see if it worked
    let emailStatus: { sent: boolean; error?: string; noKey?: boolean } = { sent: false };
    try {
      if (!process.env.RESEND_API_KEY) {
        emailStatus = { sent: false, noKey: true };
      } else {
        const [meta] = await sql.unsafe(
          `SELECT u.name as inviter_name, f.name as family_name
           FROM family_members fm
           JOIN users u ON u.id = fm.user_id
           JOIN families f ON f.id = fm.family_id
           WHERE fm.family_id = $1 AND fm.user_id = $2
           LIMIT 1`,
          [auth.session!.familyId, auth.session!.userId]
        );
        await sendFamilyInviteEmail({
          to: email,
          inviterName: meta?.inviter_name || "Someone",
          familyName: meta?.family_name || "your family",
          token,
          role: role || "caregiver",
        });
        emailStatus = { sent: true };
      }
    } catch (emailErr) {
      const msg = emailErr instanceof Error ? emailErr.message : String(emailErr);
      console.error("[INVITE-EMAIL-ERROR]", msg);
      emailStatus = { sent: false, error: msg };
    }

    return NextResponse.json({ success: true, invite, inviteUrl: `/invite/${token}`, emailStatus });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}