'use server';

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

export async function saveShippingRates(formData: FormData) {
  const entries = formData.getAll('rates') as string[];

  if (!entries || entries.length === 0) {
    redirect('/admin/shipping-rates?error=no_rates');
  }

  try {
    for (const entry of entries) {
      const rate = JSON.parse(entry) as {
        id?: string;
        service: string;
        basePrice: number;
        pricePerKg: number;
        estimatedDays: number;
        isInternational: boolean;
      };

      if (rate.id) {
        // Update existing rate
        await prisma.shippingRate.update({
          where: { id: rate.id },
          data: {
            service: rate.service,
            basePrice: Math.round(rate.basePrice),
            pricePerKg: Math.round(rate.pricePerKg),
            estimatedDays: rate.estimatedDays,
            isInternational: rate.isInternational,
          },
        });
      } else {
        // Create new rate
        await prisma.shippingRate.create({
          data: {
            service: rate.service,
            basePrice: Math.round(rate.basePrice),
            pricePerKg: Math.round(rate.pricePerKg),
            estimatedDays: rate.estimatedDays,
            isInternational: rate.isInternational,
          },
        });
      }
    }

    console.log('✓ Shipping rates updated');
    redirect('/admin/shipping-rates?success=rates_saved');
  } catch (error) {
    console.error('Error saving shipping rates:', error);
    redirect('/admin/shipping-rates?error=save_failed');
  }
}

export async function deleteShippingRate(id: string) {
  try {
    await prisma.shippingRate.delete({
      where: { id },
    });
    redirect('/admin/shipping-rates?success=rate_deleted');
  } catch (error) {
    console.error('Error deleting shipping rate:', error);
    redirect('/admin/shipping-rates?error=delete_failed');
  }
}
