'use server';

import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { sendCustomRequestNotification } from '@/lib/mail';
import { verifyTurnstileToken } from '@/lib/turnstile';
import { getClientIp } from '@/lib/rateLimit';

export async function createCustomRequest(formData: FormData) {
  const customerId = String(formData.get('customerId') ?? '').trim() || null;
  const productId = String(formData.get('productId') ?? '');
  const customerName = String(formData.get('customerName') ?? '').trim();
  const customerEmail = String(formData.get('customerEmail') ?? '').trim();
  const customerPhone = String(formData.get('customerPhone') ?? '').trim();
  const note = String(formData.get('note') ?? '').trim();
  const file = formData.get('image') as File | null;

  if (!productId || !customerName || !customerEmail || !file || file.size === 0) {
    throw new Error('Missing required fields: product, name, email, and a photo are all required.');
  }

  const ip = getClientIp(headers());
  const turnstileToken = String(formData.get('cf-turnstile-response') ?? '');
  const { success } = await verifyTurnstileToken(turnstileToken, ip);
  if (!success) {
    throw new Error('CAPTCHA verification failed — please try again.');
  }

  const product = await prisma.product.findUnique({ where: { id: productId } });
  if (!product) throw new Error('Product not found.');

  const bytes = Buffer.from(await file.arrayBuffer());
  const mimeType = file.type || 'image/png';
  const imageDataUrl = `data:${mimeType};base64,${bytes.toString('base64')}`;

  const request = await prisma.customRequest.create({
    data: {
      customerId,
      productId,
      customerName,
      customerEmail,
      customerPhone: customerPhone || null,
      imageDataUrl,
      note: note || null,
    },
  });

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';
  const adminLink = `${siteUrl}/admin/custom-requests/${request.id}`;

  await sendCustomRequestNotification({
    customerName,
    productName: product.name,
    note: note || null,
    adminLink,
  });

  redirect(`/custom-request/submitted?id=${request.id}`);
}
