import { NextResponse } from "next/server";
import { sql } from "@/db";
import { cookies } from "next/headers";
import bcrypt from "bcryptjs";
import { rateLimit, getClientIp, getRateLimitKey } from "@/lib/rate-limit";

export const dynamic = "force-dynamic";

async function hashPassword(password: string): Promise<string> {
  return await bcrypt.hash(password, 12);
}

// POST - Sign in or create first admin
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { username, password, action } = body;

    if (!username || !password) {
      return NextResponse.json({ error: "Username and password required" }, { status: 400 });
    }

    const isSignup = action === "signup";

    // Rate limiting - enable via RATE_LIMIT_ENABLED env var
    if (process.env.RATE_LIMIT_ENABLED !== "false") {
      const ip = getClientIp(request);
      const rateLimitResult = await rateLimit(
        getRateLimitKey(isSignup ? "admin-signup" : "admin-signin", ip),
        { max: isSignup ? 3 : 5, windowSec: isSignup ? 3600 : 900 }
      );
      if (!rateLimitResult.success) {
        return NextResponse.json({ error: "Too many attempts" }, { status: 429 });
      }
    }

    // First time setup (signup)
    if (isSignup) {
      // Check if admin already exists
      const existing = await sql`SELECT id FROM admins LIMIT 1`;
      if (existing && existing.length > 0) {
        return NextResponse.json({ error: "Admin already exists. Use sign in." }, { status: 400 });
      }

      const adminId = crypto.randomUUID();
      const passwordHash = await hashPassword(password);
      await sql`
        INSERT INTO admins (id, username, password_hash, role, created_at)
        VALUES (${adminId}, ${username}, ${passwordHash}, 'super_admin', NOW())
      `;

      // Create session
      const sessionToken = crypto.randomUUID();
      const expires = new Date();
      expires.setDate(expires.getDate() + 7);
      await sql`
        INSERT INTO admin_sessions (session_token, admin_id, expires)
        VALUES (${sessionToken}, ${adminId}, ${expires.toISOString()})
      `;

      const response = NextResponse.json({
        success: true,
        admin: { username, role: "super_admin" },
      });
      response.cookies.set("tia_admin_session", sessionToken, {
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax",
        maxAge: 60 * 60 * 24 * 7,
        path: "/",
      });
      return response;
    }

    // Sign in - verify against database
    const admins = await sql`
      SELECT id, username, password_hash, role FROM admins WHERE username = ${username} LIMIT 1
    `;
    const admin = admins?.[0];

    if (!admin) {
      return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
    }

    const valid = await bcrypt.compare(password, admin.password_hash);
    if (!valid) {
      return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
    }

    // Create session
    const sessionToken = crypto.randomUUID();
    const expires = new Date();
    expires.setDate(expires.getDate() + 7);
    await sql`
      INSERT INTO admin_sessions (session_token, admin_id, expires)
      VALUES (${sessionToken}, ${admin.id}, ${expires.toISOString()})
    `;

    // Update last login
    await sql`UPDATE admins SET last_login = NOW() WHERE id = ${admin.id}`;

    const response = NextResponse.json({
      success: true,
      username: admin.username,
      role: admin.role,
    });
    response.cookies.set("tia_admin_session", sessionToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60 * 24 * 7,
      path: "/",
    });
    return response;
  } catch (error) {
    console.error("Admin auth error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// DELETE - Logout (clear session)
export async function DELETE(request: Request) {
  try {
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get("tia_admin_session")?.value;

    if (sessionToken) {
      await sql`DELETE FROM admin_sessions WHERE session_token = ${sessionToken}`;
    }

    const response = NextResponse.json({ success: true });
    response.cookies.set("tia_admin_session", "", { maxAge: 0, path: "/" });
    return response;
  } catch (error) {
    console.error("Admin logout error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// GET - Check current session
export async function GET(request: Request) {
  try {
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get("tia_admin_session")?.value;

    if (!sessionToken) {
      return NextResponse.json({ authenticated: false });
    }

    // Verify session
    const sessions = await sql`
      SELECT s.admin_id, s.expires, a.username, a.role
      FROM admin_sessions s
      JOIN admins a ON a.id = s.admin_id
      WHERE s.session_token = ${sessionToken}
      AND s.expires > NOW()
      LIMIT 1
    `;

    if (!sessions || sessions.length === 0) {
      return NextResponse.json({ authenticated: false });
    }

    const session = sessions[0];
    return NextResponse.json({
      authenticated: true,
      admin: { username: session.username, role: session.role }
    });
  } catch (error) {
    console.error("Admin session check error:", error);
    return NextResponse.json({ authenticated: false });
  }
}