import { createServerClient } from "@supabase/ssr"
import { createClient } from "@supabase/supabase-js"
import { NextResponse, type NextRequest } from "next/server"

async function getUserRole(userId: string): Promise<string | null> {
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL
  const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY

  if (!supabaseUrl || !serviceRoleKey) return null

  try {
    const adminClient = createClient(supabaseUrl, serviceRoleKey, {
      auth: { autoRefreshToken: false, persistSession: false },
    })

    const { data, error } = await adminClient.from("users").select("role").eq("id", userId).single()

    if (error || !data) return null
    return data.role
  } catch {
    return null
  }
}

export async function updateSession(request: NextRequest) {
  let supabaseResponse = NextResponse.next({ request })

  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL
  const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY

  if (!supabaseUrl || !supabaseAnonKey) {
    return supabaseResponse
  }

  const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
    cookies: {
      getAll() {
        return request.cookies.getAll()
      },
      setAll(cookiesToSet) {
        cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
        supabaseResponse = NextResponse.next({ request })
        cookiesToSet.forEach(({ name, value, options }) =>
          supabaseResponse.cookies.set(name, value, {
            ...options,
            path: "/",
            maxAge: 60 * 60 * 24 * 7,
            sameSite: "lax",
            secure: process.env.NODE_ENV === "production",
          }),
        )
      },
    },
  })

  // Get current user
  let user = null
  try {
    const {
      data: { user: authUser },
      error,
    } = await supabase.auth.getUser()
    if (!error) user = authUser
  } catch {
    // Treat as not logged in
  }

  // Helper to create redirect with cookies preserved
  const createRedirect = (path: string) => {
    const url = request.nextUrl.clone()
    url.pathname = path
    const response = NextResponse.redirect(url)
    supabaseResponse.cookies.getAll().forEach((cookie) => {
      response.cookies.set(cookie.name, cookie.value, {
        path: "/",
        maxAge: 60 * 60 * 24 * 7,
        sameSite: "lax",
        secure: process.env.NODE_ENV === "production",
      })
    })
    return response
  }

  const pathname = request.nextUrl.pathname

  if (pathname.startsWith("/admin")) {
    if (!user) {
      return createRedirect("/auth/login")
    }
    const role = await getUserRole(user.id)
    if (role !== "admin") {
      return createRedirect("/dashboard")
    }
  }

  // Protect dashboard routes - organizer and admin allowed
  if (pathname.startsWith("/dashboard")) {
    if (!user) {
      return createRedirect("/auth/login")
    }
    const role = await getUserRole(user.id)
    if (role !== "organizer" && role !== "admin") {
      if (role === "customer") {
        return createRedirect("/profile")
      }
      return createRedirect("/auth/login")
    }
  }

  // Protect profile routes - customers only
  if (pathname.startsWith("/profile")) {
    if (!user) {
      return createRedirect("/auth/customer-login")
    }
    const role = await getUserRole(user.id)
    // Only customers can access profile routes
    if (role !== "customer") {
      // Redirect organizers and admins to dashboard
      if (role === "organizer" || role === "admin") {
        return createRedirect("/dashboard")
      }
      // Redirect staff to staff page
      if (role === "staff") {
        return createRedirect("/staff")
      }
      // Unknown role, redirect to login
      return createRedirect("/auth/login")
    }
  }

  // Protect staff routes - staff role only
  if (pathname.startsWith("/staff")) {
    if (!user) {
      return createRedirect("/auth/staff-login")
    }
    const role = await getUserRole(user.id)
    if (role !== "staff" && role !== "admin") {
      return createRedirect("/auth/staff-login")
    }
  }

  return supabaseResponse
}
