'use server';

import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { getCurrentUser, verifyPassword } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * Self-serve account deletion.
 *
 * Refused for the last admin (we can't leave the instance with no
 * admin). Refused if the typed-confirmation phrase is wrong (defense
 * against a stolen-session attacker nuking the account in one click).
 * Cascades through Prisma (onDelete: Cascade on every relation owned
 * by User) so workouts, exercises, sessions, preferences, etc. all
 * disappear in one shot. Clears the session cookie before redirecting
 * to /auth/login.
 */

const REQUIRED_PHRASE = 'delete my account';

export async function deleteMyAccountAction(
  password: string,
  confirmationPhrase: string,
): Promise<{ error?: string }> {
  try {
    const me = await getCurrentUser();
    if (!me) return { error: 'Not signed in.' };

    if (confirmationPhrase.trim().toLowerCase() !== REQUIRED_PHRASE) {
      return {
        error: `To confirm, type the exact phrase: "${REQUIRED_PHRASE}".`,
      };
    }

    const ok = await verifyPassword(password, me.passwordHash);
    if (!ok) {
      return { error: 'Password is incorrect.' };
    }

    if (me.isAdmin) {
      const adminCount = await prisma.user.count({ where: { isAdmin: true } });
      if (adminCount <= 1) {
        return {
          error:
            'Cannot delete the last admin. Promote another user to admin first, then try again.',
        };
      }
    }

    await prisma.user.delete({ where: { id: me.id } });

    const cookieStore = await cookies();
    cookieStore.delete('sessionToken');
  } catch (err) {
    console.error('deleteMyAccount error:', err);
    return { error: 'An error occurred while deleting your account.' };
  }

  // Redirect must be outside the try/catch — Next.js implements redirect
  // by throwing a special value, and our catch would swallow it.
  redirect('/auth/login');
}
