import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg";
import { requireAdmin, getSession } from "@/lib/auth-utils";
import { sendInvitationEmail } from "@/lib/services/email";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// POST /api/admin/users/invite - Send invitation email
export async function POST(request: NextRequest) {
  const { session, error } = await requireAdmin();
  if (error) return error;

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

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

    // Check if user already exists
    const existingUser = await pool.query(
      'SELECT id FROM "user" WHERE email = $1',
      [email]
    );

    if (existingUser.rows.length > 0) {
      return NextResponse.json(
        { error: "User with this email already exists" },
        { status: 409 }
      );
    }

    // Create the user with requires_setup flag
    const id = crypto.randomUUID();
    await pool.query(
      `INSERT INTO "user" (id, name, email, role, email_verified, requires_setup, created_at, updated_at)
       VALUES ($1, $2, $3, $4, false, true, NOW(), NOW())`,
      [id, name || email.split("@")[0], email, role]
    );

    // Generate invitation URL (magic link)
    const baseUrl = process.env.BETTER_AUTH_URL || "http://localhost:3000";
    const inviteUrl = `${baseUrl}/auth/sign-in?email=${encodeURIComponent(email)}`;

    // Get inviter name
    const inviterName = session?.user.name || "An administrator";

    // Send invitation email
    await sendInvitationEmail({
      email,
      inviterName,
      url: inviteUrl,
    });

    return NextResponse.json({
      success: true,
      message: "Invitation sent successfully",
    });
  } catch (error) {
    console.error("Error sending invitation:", error);
    return NextResponse.json(
      { error: "Failed to send invitation" },
      { status: 500 }
    );
  }
}
