'use server';

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

export async function createPromotion(formData: FormData) {
  const message = String(formData.get('message') ?? '').trim();
  const discountPercent = Math.round(Number(formData.get('discountPercent') ?? 0));
  const scope = String(formData.get('scope') ?? 'ALL') === 'SPECIFIC' ? 'SPECIFIC' : 'ALL';
  const productIds = formData.getAll('productIds').map(String).filter(Boolean);
  const startInput = String(formData.get('startsAt') ?? '').trim();
  const endInput = String(formData.get('endsAt') ?? '').trim();

  if (!message) throw new Error('A banner message is required.');
  if (!discountPercent || discountPercent < 1 || discountPercent > 100) {
    throw new Error('Discount must be between 1 and 100 percent.');
  }
  if (scope === 'SPECIFIC' && productIds.length === 0) {
    throw new Error('Pick at least one product, or choose "All items" instead.');
  }

  await prisma.promotion.create({
    data: {
      message,
      discountPercent,
      scope,
      startsAt: startInput ? new Date(startInput) : null,
      endsAt: endInput ? new Date(`${endInput}T23:59:59`) : null,
      products: scope === 'SPECIFIC' ? { connect: productIds.map((id) => ({ id })) } : undefined,
    },
  });

  redirect('/admin/promotions');
}

export async function updatePromotion(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  const message = String(formData.get('message') ?? '').trim();
  const discountPercent = Math.round(Number(formData.get('discountPercent') ?? 0));
  const scope = String(formData.get('scope') ?? 'ALL') === 'SPECIFIC' ? 'SPECIFIC' : 'ALL';
  const productIds = formData.getAll('productIds').map(String).filter(Boolean);
  const startInput = String(formData.get('startsAt') ?? '').trim();
  const endInput = String(formData.get('endsAt') ?? '').trim();

  if (!id) throw new Error('Missing promotion id.');
  if (!message) throw new Error('A banner message is required.');
  if (!discountPercent || discountPercent < 1 || discountPercent > 100) {
    throw new Error('Discount must be between 1 and 100 percent.');
  }
  if (scope === 'SPECIFIC' && productIds.length === 0) {
    throw new Error('Pick at least one product, or choose "All items" instead.');
  }

  await prisma.promotion.update({
    where: { id },
    data: {
      message,
      discountPercent,
      scope,
      startsAt: startInput ? new Date(startInput) : null,
      endsAt: endInput ? new Date(`${endInput}T23:59:59`) : null,
      // `set` replaces the full connection list in one go — correctly handles
      // switching scope (SPECIFIC -> ALL clears it) and adding/removing products.
      products: { set: scope === 'SPECIFIC' ? productIds.map((pid) => ({ id: pid })) : [] },
    },
  });

  redirect('/admin/promotions');
}

export async function deletePromotion(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  if (!id) return;

  await prisma.promotion.delete({ where: { id } });
  redirect('/admin/promotions');
}
