import type { NextRequest } from "next/server"
import { sql } from "@/lib/db"

export async function getAdminUser(request: NextRequest): Promise<string | null> {
  try {
    // Try to get token from Authorization header first
    const authHeader = request.headers.get("authorization")

    let token: string | null = null

    if (authHeader?.startsWith("Bearer ")) {
      token = authHeader.substring(7)
    }

    // Fallback to cookie
    if (!token) {
      const sessionCookie = request.cookies.get("session")
      if (sessionCookie) {
        try {
          const session = JSON.parse(sessionCookie.value)
          token = session.token
        } catch {
          // Invalid cookie format
        }
      }
    }

    if (!token) {
      return null
    }

    // Validate token against user_sessions table
    const sessions = await sql`
      SELECT us.user_id, u.role 
      FROM user_sessions us
      JOIN users u ON u.id = us.user_id
      WHERE us.token = ${token}
      AND us.expires_at > NOW()
    `

    if (sessions.length === 0) {
      return null
    }

    // Check if user is admin
    if (sessions[0].role !== "admin") {
      return null
    }

    return sessions[0].user_id
  } catch {
    return null
  }
}
