import { NextResponse } from "next/server"
import { createClient } from "@supabase/supabase-js"
import type { User } from "@supabase/supabase-js"
import { buildDemoPassword, isHumandEmail, normalizeHumandEmail } from "@/lib/auth/poc-auth"
import { getSupabaseAdminEnv } from "@/lib/supabase/env.server"

const DEFAULT_ADMIN_EMAILS =
  "sebastian.favaron@humand.co,lucia.strozza@humand.co,gaston.rios@humand.co,marcos.palacio@humand.co"

type LoginBody = {
  email?: string
}

async function findAuthUserByEmail(
  admin: ReturnType<typeof createClient>,
  email: string,
): Promise<User | null> {
  const perPage = 200

  for (let page = 1; page <= 10; page += 1) {
    const { data, error } = await admin.auth.admin.listUsers({ page, perPage })
    if (error) {
      throw error
    }

    const users = data.users ?? []
    const match = users.find((user) => user.email?.toLowerCase() === email)
    if (match) {
      return match
    }

    if (users.length < perPage) {
      break
    }
  }

  return null
}

export async function POST(request: Request) {
  const body = (await request.json().catch(() => ({}))) as LoginBody
  const normalizedEmail = normalizeHumandEmail(body.email ?? "")

  if (!normalizedEmail || !isHumandEmail(normalizedEmail)) {
    return NextResponse.json(
      { error: "Solo se permiten emails con dominio @humand.co" },
      { status: 400 },
    )
  }

  let supabaseUrl: string
  let serviceRoleKey: string
  try {
    const env = getSupabaseAdminEnv()
    supabaseUrl = env.url
    serviceRoleKey = env.serviceRoleKey
  } catch (error) {
    const message =
      error instanceof Error
        ? error.message
        : "Falta configurar NEXT_PUBLIC_SUPABASE_URL y SUPABASE_SERVICE_ROLE_KEY en el entorno"
    return NextResponse.json({ error: message }, { status: 500 })
  }

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

  try {
    const password = buildDemoPassword(normalizedEmail)
    const adminEmails = new Set(
      (process.env.DEMO_ADMIN_EMAILS ?? DEFAULT_ADMIN_EMAILS)
        .split(",")
        .map((email) => email.trim().toLowerCase())
        .filter(Boolean),
    )
    const role = adminEmails.has(normalizedEmail) ? "admin" : "user"
    const displayName = normalizedEmail.split("@")[0] || "Usuario demo"
    let authUser = await findAuthUserByEmail(admin, normalizedEmail)

    if (!authUser) {
      const { data, error } = await admin.auth.admin.createUser({
        email: normalizedEmail,
        password,
        email_confirm: true,
        user_metadata: {
          full_name: displayName,
          role,
        },
      })

      if (error) {
        throw error
      }

      authUser = data.user
    } else {
      const { error } = await admin.auth.admin.updateUserById(authUser.id, {
        password,
        email_confirm: true,
        user_metadata: {
          full_name: displayName,
          role,
        },
      })

      if (error) {
        throw error
      }
    }

    if (!authUser) {
      return NextResponse.json({ error: "No se pudo preparar el usuario demo" }, { status: 500 })
    }

    const { error: profileError } = await admin.from("users").upsert(
      {
        id: authUser.id,
        email: normalizedEmail,
        full_name: displayName,
        role,
        is_active: true,
      },
      { onConflict: "id" },
    )

    if (profileError) {
      throw profileError
    }

    return NextResponse.json({ ok: true })
  } catch (error) {
    const message = error instanceof Error ? "No se pudo preparar el usuario demo" : "Error preparando usuario demo"
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
