import { NextResponse } from "next/server";
import { sql } from "@/db";
import { cookies } from "next/headers";

// For onboarding - auth via custom session (not next-auth)
export async function POST(request: Request) {
  const sessionToken = (await cookies()).get("tia_session")?.value;

  if (!sessionToken) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // Get user from session
  const sessions = await sql`
    SELECT user_id FROM sessions WHERE session_token = ${sessionToken} AND expires > NOW()
  `;

  if (!sessions || sessions.length === 0) {
    return NextResponse.json({ error: "Invalid session" }, { status: 401 });
  }

  const userId = sessions[0].user_id;

  const body = await request.json();
  const { familyName, memberName, phone, childName, birthDate, sex } = body;

  try {
    // Save the parent's name + optional phone onto their user record.
    // Phone: keep leading + then digits; store null when blank/invalid.
    let normalizedPhone: string | null = null;
    if (phone && typeof phone === "string") {
      const cleaned = phone.trim().replace(/[^\d+]/g, "").replace(/(?!^)\+/g, "");
      const digits = cleaned.replace(/\D/g, "");
      if (digits.length >= 8 && digits.length <= 15) normalizedPhone = cleaned;
    }
    await sql`
      UPDATE users
      SET name = COALESCE(${memberName || null}, name), phone = ${normalizedPhone}, updated_at = NOW()
      WHERE id = ${userId}
    `;

    // Create family
    const familyId = crypto.randomUUID();
    await sql.unsafe(
      `INSERT INTO families (id, name, created_at, updated_at) VALUES ($1, $2, NOW(), NOW())`,
      [familyId, familyName || "The Family"]
    );

    // Add member
    await sql.unsafe(
      `INSERT INTO family_members (id, family_id, user_id, role, created_at) VALUES ($1, $2, $3, 'admin', NOW())`,
      [crypto.randomUUID(), familyId, userId]
    );

    // Create child
    const childId = crypto.randomUUID();
    const birth = new Date(birthDate);
    const months = Math.floor((Date.now() - birth.getTime()) / (1000 * 60 * 60 * 24 * 30));
    let stage = "newborn";
    if (months >= 36) stage = "preschool";
    else if (months >= 24) stage = "toddler_late";
    else if (months >= 12) stage = "toddler_early";
    else if (months >= 6) stage = "solids_start";
    else if (months >= 3) stage = "infant";

    await sql.unsafe(
      `INSERT INTO children (id, family_id, name, birth_date, sex, stage, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())`,
      [childId, familyId, childName, birth.toISOString(), sex, stage]
    );

    return NextResponse.json({ success: true, childId, familyId });
  } catch (error) {
    console.error("Onboarding error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}