import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
import { pgGetMaterials, pgSaveInvoices, pgGetInvoices } from '@/lib/postgres/data-access';

// Rate limiting: simple in-memory store (resets on server restart)
// For production, use Redis or similar
const requestCounts = new Map<string, { count: number; resetAt: number }>();

function checkRateLimit(ip: string): boolean {
  const now = Date.now();
  const windowMs = 60 * 1000; // 1 minute
  const maxRequests = 10;
  const entry = requestCounts.get(ip);
  if (!entry || entry.resetAt < now) {
    requestCounts.set(ip, { count: 1, resetAt: now + windowMs });
    return true;
  }
  if (entry.count >= maxRequests) return false;
  entry.count++;
  return true;
}

function getClientIp(request: NextRequest): string {
  return (
    request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
    request.headers.get('x-real-ip') ||
    'unknown'
  );
}

export async function POST(request: NextRequest) {
  try {
    const ip = getClientIp(request);
    if (!checkRateLimit(ip)) {
      return NextResponse.json({ error: 'طلبات كثيرة، يرجى الانتظار قليلاً' }, { status: 429 });
    }

    const body = await request.json();
    const { customerName, customerAddress, customerPhone, customerNote, items } = body;

    // Validate required fields
    if (!customerName || typeof customerName !== 'string' || customerName.trim().length === 0) {
      return NextResponse.json({ error: 'الاسم مطلوب' }, { status: 400 });
    }
    if (!customerAddress || typeof customerAddress !== 'string' || customerAddress.trim().length === 0) {
      return NextResponse.json({ error: 'العنوان مطلوب' }, { status: 400 });
    }
    if (!customerPhone || typeof customerPhone !== 'string' || customerPhone.trim().length === 0) {
      return NextResponse.json({ error: 'رقم الجوال مطلوب' }, { status: 400 });
    }
    if (!Array.isArray(items) || items.length === 0) {
      return NextResponse.json({ error: 'يجب اختيار منتج واحد على الأقل' }, { status: 400 });
    }
    if (items.length > 100) {
      return NextResponse.json({ error: 'عدد المنتجات تجاوز الحد المسموح' }, { status: 400 });
    }

    // Sanitize customer info
    const name = String(customerName).trim().slice(0, 100);
    const address = String(customerAddress).trim().slice(0, 300);
    const phone = String(customerPhone).trim().replace(/[^\d+\s-]/g, '').slice(0, 20);
    const note = customerNote ? String(customerNote).trim().slice(0, 500) : '';

    // Fetch all materials and verify items are store-enabled
    const materialsResult = await pgGetMaterials({ page: 1, pageSize: 5000 });
    const allMaterials = (materialsResult.items || []) as any[];
    const materialsMap = new Map(allMaterials.map((m) => [String(m.id || ''), m]));

    const invoiceLines: any[] = [];
    let grandTotal = 0;

    for (const orderItem of items) {
      const materialId = String(orderItem.materialId || '').trim();
      const quantity = Number(orderItem.quantity || 0);

      if (!materialId || quantity <= 0 || !Number.isFinite(quantity) || quantity > 9999) {
        return NextResponse.json({ error: `بيانات صنف غير صالحة` }, { status: 400 });
      }

      const material = materialsMap.get(materialId);
      if (!material) {
        return NextResponse.json({ error: `الصنف غير موجود` }, { status: 400 });
      }
      if (material.storeEnabled !== true && material.storeEnabled !== 'true') {
        return NextResponse.json({ error: `الصنف غير متاح في المتجر` }, { status: 400 });
      }

      // Use server-side price — never trust client price
      const unitPrice = Number(material.salePrice || 0);
      const lineTotal = unitPrice * quantity;
      grandTotal += lineTotal;

      invoiceLines.push({
        materialId: material.id,
        materialName: String(material.name || ''),
        quantity,
        unitPrice,
        total: lineTotal,
        unit: String(material.primaryUnit || ''),
      });
    }

    // Generate invoice number: get count of existing store invoices + 1
    const existingResult = await pgGetInvoices({ page: 1, pageSize: 1 });
    const totalInvoices = existingResult.totalItems || 0;
    const invoiceSeq = String(totalInvoices + 1).padStart(4, '0');
    const year = new Date().getFullYear();
    const invoiceNumber = `STORE/${year}/${invoiceSeq}`;

    const invoiceId = `inv-store-${randomUUID()}`;
    const now = new Date().toISOString();

    const notes = [
      `مصدر: متجر إلكتروني`,
      `اسم: ${name}`,
      `عنوان: ${address}`,
      `جوال: ${phone}`,
      note ? `ملاحظة: ${note}` : null,
    ]
      .filter(Boolean)
      .join(' | ');

    const invoice = {
      id: invoiceId,
      invoiceNumber,
      type: 'sale',
      source: 'store',
      storeStatus: 'pending',
      date: now,
      customerId: '',
      customerName: name,
      notes,
      items: invoiceLines,
      grandTotal,
      amountPaid: 0,
      amountDue: grandTotal,
      status: 'active',
      createdAt: now,
      updatedAt: now,
      storeCustomerAddress: address,
      storeCustomerPhone: phone,
    };

    await pgSaveInvoices([invoice]);

    return NextResponse.json({ success: true, invoiceNumber, invoiceId });
  } catch (error: any) {
    console.error('[store/checkout] Error:', error);
    return NextResponse.json({ error: 'حدث خطأ في الخادم، يرجى المحاولة لاحقاً' }, { status: 500 });
  }
}
