import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { sql } from "@/db";
import bcrypt from "bcryptjs";

// GET all users
export async function GET(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {

    // Get all users
    const users = await sql`
      SELECT
        u.id,
        u.email,
        u.name,
        u.phone,
        u.password_hash,
        fm.family_id,
        fm.id as member_id,
        f.name as family_name,
        u.created_at
      FROM users u
      LEFT JOIN family_members fm ON fm.user_id = u.id
      LEFT JOIN families f ON f.id = fm.family_id
      ORDER BY u.created_at DESC
    `;

    return NextResponse.json({
      users: users.map((u: any) => ({
        id: u.id,
        email: u.email,
        name: u.name,
        phone: u.phone || null,
        hasPassword: !!u.password_hash,
        familyId: u.family_id,
        memberId: u.member_id,
        familyName: u.family_name,
        createdAt: u.created_at ? new Date(u.created_at).toISOString() : null,
      })),
    });
  } catch (error) {
    console.error("Admin users error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// Create user or add to family
export async function POST(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {

    const body = await request.json();
    const { email, familyId, role, name } = body;

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

    // Check if user exists
    let existing = await sql`SELECT id FROM users WHERE email = ${email}`;
    let userId = existing?.[0]?.id;

    if (!userId) {
      userId = crypto.randomUUID();
      await sql`
        INSERT INTO users (id, email, name, created_at, updated_at)
        VALUES (${userId}, ${email}, ${name || email}, NOW(), NOW())
      `;
    }

    // Add to family if familyId provided
    if (familyId) {
      await sql`
        INSERT INTO family_members (id, family_id, user_id, role, display_name, created_at)
        VALUES (${crypto.randomUUID()}, ${familyId}, ${userId}, ${role || 'caregiver'}, ${name || email}, NOW())
        ON CONFLICT DO NOTHING
      `;
    }

    return NextResponse.json({ success: true, userId });
  } catch (error) {
    console.error("Admin users error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// Update user password or other fields
export async function PATCH(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {

    const body = await request.json();
    const { userId, password } = body;

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

    if (password) {
      const passwordHash = await bcrypt.hash(password, 12);
      await sql`
        UPDATE users SET password_hash = ${passwordHash}, password_updated_at = NOW(), updated_at = NOW()
        WHERE id = ${userId}
      `;
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Admin password update error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// Remove user from family or delete entirely
export async function DELETE(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const { searchParams } = new URL(request.url);
    const memberId = searchParams.get("memberId");
    const userId = searchParams.get("userId");

    if (memberId) {
      await sql`DELETE FROM family_members WHERE id = ${memberId}`;
    } else if (userId) {
      // Must clean up FK-constrained tables before deleting user
      // (all have ON DELETE no action constraints)
      await sql`DELETE FROM sessions WHERE user_id = ${userId}`;
      await sql`DELETE FROM accounts WHERE user_id = ${userId}`;
      await sql`UPDATE support_tickets SET user_id = NULL WHERE user_id = ${userId}`;
      await sql`DELETE FROM family_members WHERE user_id = ${userId}`;
      await sql`DELETE FROM users WHERE id = ${userId}`;
    } else {
      return NextResponse.json({ error: "memberId or userId required" }, { status: 400 });
    }

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