"use server"

import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { hash, compare } from "bcryptjs"
import { z } from "zod"

export type ChangePasswordState = { error?: string; success?: boolean }

const changePasswordSchema = z.object({
  currentPassword: z.string().optional(),
  newPassword: z.string().min(8, "8 caractères minimum"),
  confirmPassword: z.string(),
})

export async function changePassword(
  _prev: ChangePasswordState,
  formData: FormData
): Promise<ChangePasswordState> {
  const session = await auth()
  if (!session?.user) return { error: "Non authentifié" }

  const parsed = changePasswordSchema.safeParse({
    currentPassword: formData.get("currentPassword") || undefined,
    newPassword: formData.get("newPassword"),
    confirmPassword: formData.get("confirmPassword"),
  })
  if (!parsed.success) {
    return { error: parsed.error.issues[0]?.message ?? "Données invalides" }
  }
  const { currentPassword, newPassword, confirmPassword } = parsed.data

  if (newPassword !== confirmPassword) {
    return { error: "Les mots de passe ne correspondent pas" }
  }

  const user = await db.user.findUnique({ where: { id: session.user.id } })
  if (!user) return { error: "Compte introuvable" }

  if (user.password) {
    if (!currentPassword) return { error: "Mot de passe actuel requis" }
    const valid = await compare(currentPassword, user.password)
    if (!valid) return { error: "Mot de passe actuel incorrect" }
  }

  if (user.password && (await compare(newPassword, user.password))) {
    return { error: "Le nouveau mot de passe doit différer de l'actuel" }
  }

  const hashed = await hash(newPassword, 12)
  await db.user.update({ where: { id: user.id }, data: { password: hashed } })

  return { success: true }
}
