'use server';

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

const AUTO_ARCHIVE_DAYS = 30;

// Runs on every visit to the orders list — sweeps anything past the cutoff into
// the archive. No cron/scheduled task needed for a tool at this scale; this is
// "close enough" to real auto-archiving without extra infrastructure.
export async function autoArchiveOldOrders() {
  const cutoff = new Date();
  cutoff.setDate(cutoff.getDate() - AUTO_ARCHIVE_DAYS);

  await prisma.order.updateMany({
    where: {
      archived: false,
      status: { in: ['PAID', 'FAILED'] }, // never auto-archive something still PENDING
      createdAt: { lt: cutoff },
    },
    data: { archived: true },
  });
}

export async function archiveOrder(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  if (!id) return;
  await prisma.order.update({ where: { id }, data: { archived: true } });
  redirect('/admin/orders');
}

export async function unarchiveOrder(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  if (!id) return;
  await prisma.order.update({ where: { id }, data: { archived: false } });
  redirect('/admin/orders?archived=1');
}
