import { z } from 'zod'

const AuthSchema = z.object({
  password: z.string().min(1).max(100),
})

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const parsed = AuthSchema.safeParse(body)

  if (!parsed.success) {
    throw createError({ statusCode: 422, statusMessage: 'Mot de passe invalide' })
  }

  const config = useRuntimeConfig()
  const expected = config.codevPassword || 'merci'

  const isAdmin = parsed.data.password.trim().toLowerCase() === (config.codevAdminPassword || 'admin2026').trim().toLowerCase()
  const isUser = parsed.data.password.trim().toLowerCase() === expected.trim().toLowerCase()

  if (!isAdmin && !isUser) {
    throw createError({ statusCode: 401, statusMessage: 'Mauvais mot de passe' })
  }

  // Cookie session (user + admin)
  setCookie(event, 'codev_session', 'ok', {
    httpOnly: true,
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
    maxAge: 60 * 60 * 24, // 24h
    path: '/',
  })

  // Cookie admin si mot de passe admin
  if (isAdmin) {
    setCookie(event, 'codev_admin', 'ok', {
      httpOnly: true,
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
      maxAge: 60 * 60 * 24, // 24h
      path: '/',
    })
  }

  return { status: 200, ok: true, admin: isAdmin }
})
