'use server';

import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { prisma } from '@/lib/prisma';
import { sendWhatsAppMessage } from '@/lib/whatsapp';

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');
}

export async function updateOrderTracking(formData: FormData) {
  const id = String(formData.get('orderId') ?? '');
  const status = String(formData.get('status') ?? 'PENDING');
  const carrier = formData.get('carrier') ? String(formData.get('carrier')) : null;
  const trackingNumber = formData.get('trackingNumber') ? String(formData.get('trackingNumber')) : null;
  const estimatedDeliveryDate = formData.get('estimatedDeliveryDate') ? new Date(String(formData.get('estimatedDeliveryDate'))) : null;
  const collectedByCustomer = formData.has('collectedByCustomer');
  const readyForCollection = formData.has('readyForCollection') && formData.get('readyForCollection') === 'true';
  const phoneNumber = formData.get('phoneNumber') ? String(formData.get('phoneNumber')) : null;

  console.log('✓ Order update:', { id, status, collectedByCustomer, readyForCollection });

  if (!id) return;

  const order = await prisma.order.findUnique({
    where: { id },
    include: { customer: true },
  });

  if (!order) return;

  // Update the order
  await prisma.order.update({
    where: { id },
    data: {
      status,
      carrier,
      trackingNumber,
      estimatedDeliveryDate,
      collectedByCustomer,
      readyForCollection: readyForCollection || undefined,
      phoneNumber: phoneNumber || order.phoneNumber || undefined,
    },
  });

  // Send WhatsApp notification if marking ready for collection
  if (readyForCollection && !order.readyForCollection) {
    const phone = phoneNumber || order.phoneNumber;
    if (phone) {
      await sendWhatsAppMessage(
        phone,
        `Hi! 👋 Your order from Craft2Prints is ready for collection. Please come pick it up at your earliest convenience. Thanks!`
      );
    } else {
      console.warn(`No phone number for order ${id} - WhatsApp message not sent`);
    }
  }

  // Revalidate the page to show updated data
  revalidatePath(`/admin/orders/${id}`);
  revalidatePath(`/admin/orders`);

  // Redirect back to orders list if marking as complete
  if (status === 'DELIVERED') {
    redirect('/admin/orders');
  }
}
