'use server'

import { auth, getSanitizedHeaders } from '@/lib/auth'
import { prisma } from '@innungsapp/shared'
// @ts-ignore
import { hashPassword } from 'better-auth/crypto'

export async function changePasswordAndDisableMustChange(prevState: any, formData: FormData) {
    const newPassword = formData.get('newPassword') as string
    const confirmPassword = formData.get('confirmPassword') as string

    if (newPassword !== confirmPassword) {
        return { success: false, error: 'Passwörter stimmen nicht überein.' }
    }

    if (newPassword.length < 8) {
        return { success: false, error: 'Das Passwort muss mindestens 8 Zeichen lang sein.' }
    }

    const sanitizedHeaders = await getSanitizedHeaders()
    const session = await auth.api.getSession({ headers: sanitizedHeaders })
    if (!session?.user) {
        return { success: false, error: 'Nicht authentifiziert.' }
    }

    const userId = session.user.id

    // Hash and save new password directly — user is already authenticated so no old password needed
    const newHash = await hashPassword(newPassword)

    const credAccount = await prisma.account.findFirst({
        where: { userId, providerId: 'credential' },
    })

    if (credAccount) {
        await prisma.account.update({
            where: { id: credAccount.id },
            data: { password: newHash },
        })
    } else {
        await prisma.account.create({
            data: {
                id: crypto.randomUUID(),
                accountId: userId,
                providerId: 'credential',
                userId,
                password: newHash,
            },
        })
    }

    // Clear mustChangePassword
    await prisma.user.update({
        where: { id: userId },
        data: { mustChangePassword: false },
    })

    // Sign out so the user logs in fresh with the new password
    try {
        await auth.api.signOut({ headers: sanitizedHeaders })
    } catch {
        // ignore
    }

    return {
        success: true,
        error: '',
        redirectTo: `/login?message=password_changed&callbackUrl=/dashboard`,
    }
}
