'use server';

import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';

export async function createExpense(formData: FormData) {
  const dateInput = String(formData.get('date') ?? '').trim();
  const description = String(formData.get('description') ?? '').trim();
  const category = String(formData.get('category') ?? 'Other').trim();
  const amountInput = String(formData.get('amount') ?? '0').trim();
  const notes = String(formData.get('notes') ?? '').trim();
  const receipt = formData.get('receipt') as File | null;

  if (!description) throw new Error('Description is required.');
  const amount = Math.max(0, Math.round(Number(amountInput || '0') * 100));
  if (!amount) throw new Error('Amount must be greater than 0.');

  let receiptDataUrl: string | null = null;
  let receiptFileName: string | null = null;
  if (receipt && receipt.size > 0) {
    if (receipt.size > 8 * 1024 * 1024) {
      throw new Error('Receipt file is too large — keep it under 8 MB.');
    }
    const bytes = Buffer.from(await receipt.arrayBuffer());
    const mimeType = receipt.type || 'application/octet-stream';
    receiptDataUrl = `data:${mimeType};base64,${bytes.toString('base64')}`;
    receiptFileName = receipt.name || 'receipt';
  }

  await prisma.expense.create({
    data: {
      date: dateInput ? new Date(dateInput) : new Date(),
      description,
      category,
      amount,
      receiptDataUrl,
      receiptFileName,
      notes: notes || null,
    },
  });

  redirect('/admin/accounts/expenses');
}

export async function deleteExpense(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  if (!id) return;
  await prisma.expense.delete({ where: { id } });
  redirect('/admin/accounts/expenses');
}
