"use server";

import { redirect } from "next/navigation";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { getSessionClientId, verifyPassword, destroySession } from "@/lib/auth";
import { clientHasInvoices, hardDeleteClient } from "@/lib/accountDeletion";
import { logTeamActivity } from "@/lib/teamActivity";
import { getSettings } from "@/lib/settings";
import { sendMail } from "@/lib/mail";
import { emailShell } from "@/lib/emailTemplate";

type DeletionState = { error?: string; requested?: boolean };

export async function requestAccountDeletionAction(_prev: DeletionState, formData: FormData): Promise<DeletionState> {
  const locale = String(formData.get("locale") || "de");
  const password = String(formData.get("password") || "");

  const clientId = await getSessionClientId();
  if (!clientId) return { error: locale === "en" ? "Please log in." : "Bitte logge dich ein." };

  await connectDB();
  const client = await Client.findById(clientId);
  if (!client || client.role !== "client") {
    return { error: locale === "en" ? "Account not found." : "Konto nicht gefunden." };
  }

  const valid = await verifyPassword(password, client.passwordHash);
  if (!valid) return { error: locale === "en" ? "Incorrect password." : "Passwort falsch." };

  const hasInvoices = await clientHasInvoices(clientId);

  if (!hasInvoices) {
    await hardDeleteClient(clientId);
    await destroySession();
    redirect(`/${locale}`);
  }

  if (!client.deletionRequestedAt) {
    client.deletionRequestedAt = new Date();
    await client.save();
    await logTeamActivity("Kunde hat Kontolöschung beantragt", client.name);

    const settings = await getSettings();
    const adminEmail = settings.invoiceSettings?.email || settings.socialLinks?.email;
    if (adminEmail) {
      await sendMail(
        adminEmail,
        "Kontolöschung beantragt — Rakku Photography",
        await emailShell({
          heading: "Kontolöschung beantragt",
          bodyHtml: `<p style="margin:0;">${client.name} (${client.email}) hat die Löschung seines Kontos beantragt. Wegen vorhandener Rechnungen (Aufbewahrungspflicht) kann das Konto nicht automatisch gelöscht werden — bitte im Admin-Bereich prüfen und anonymisieren.</p>`,
          buttonLabel: "Kundenakte öffnen",
          buttonUrl: `${process.env.SITE_URL}/de/admin/clients/${client._id}`,
          footerNote: "Diese Mail ging automatisch raus, weil ein Kunde die Löschung seines Kontos beantragt hat.",
        })
      );
    }
  }

  return { requested: true };
}

export async function cancelAccountDeletionRequestAction(): Promise<void> {
  const clientId = await getSessionClientId();
  if (!clientId) return;
  await connectDB();
  await Client.updateOne({ _id: clientId, role: "client" }, { $set: { deletionRequestedAt: null } });
}
