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

/**
 * Verify admin session in server components using next/headers cookies.
 */
export async function verifyAdminSession(): Promise<{
  success: boolean;
  admin?: { username: string; role: string };
}> {
  try {
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get("tia_admin_session")?.value;
    if (!sessionToken) return { success: false };

    const sessions = await sql.unsafe(
      `SELECT admins.username, admins.role FROM admin_sessions
       JOIN admins ON admins.id = admin_sessions.admin_id
       WHERE admin_sessions.session_token = $1 AND admin_sessions.expires > NOW()
       LIMIT 1`,
      [sessionToken]
    );
    if (!sessions || sessions.length === 0) return { success: false };
    const row = sessions[0] as unknown as { username: string; role: string };
    return { success: true, admin: { username: row.username, role: row.role } };
  } catch {
    return { success: false };
  }
}

/**
 * Validate admin session from tia_admin_session cookie
 */
export async function requireAdmin(request: Request): Promise<{
  success: boolean;
  error?: string;
  status?: number;
  admin?: any;
}> {
  const cookieHeader = request.headers.get("cookie");
  const sessionToken = cookieHeader?.match(/tia_admin_session=([^;]+)/)?.[1];

  if (!sessionToken) {
    return { success: false, error: "Not authenticated", status: 401 };
  }

  try {
    const sessions = await sql.unsafe(
      `SELECT admin_sessions.id, admins.username, admins.role FROM admin_sessions
       JOIN admins ON admins.id = admin_sessions.admin_id
       WHERE admin_sessions.session_token = $1 AND admin_sessions.expires > NOW()`,
      [sessionToken]
    );

    if (!sessions || sessions.length === 0) {
      return { success: false, error: "Invalid or expired session", status: 401 };
    }

    return { success: true, admin: sessions[0] };
  } catch (error) {
    console.error("Admin auth error:", error);
    return { success: false, error: "Internal error", status: 500 };
  }
}