
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/db';

// GET all pricing rates
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Only authenticated CRM users can view pricing rates
    if (session.user.role === 'CUSTOMER') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const rates = await prisma.pricingRate.findMany({
      where: { isActive: true },
      orderBy: { serviceType: 'asc' }
    });

    return NextResponse.json({ rates });
  } catch (error) {
    console.error('Error fetching pricing rates:', error);
    return NextResponse.json({ error: 'Failed to fetch pricing rates' }, { status: 500 });
  }
}

// POST - Create or update pricing rates
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Only admin can update pricing rates
    if (session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden - Admin only' }, { status: 403 });
    }

    const body = await req.json();
    const { rates } = body;

    if (!rates || !Array.isArray(rates)) {
      return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
    }

    // Update rates one by one
    for (const rateData of rates) {
      await prisma.pricingRate.upsert({
        where: { serviceType: rateData.serviceType },
        update: {
          rate: rateData.rate,
          unit: rateData.unit,
          currency: rateData.currency || 'ZAR',
          description: rateData.description
        },
        create: {
          serviceType: rateData.serviceType,
          rate: rateData.rate,
          unit: rateData.unit,
          currency: rateData.currency || 'ZAR',
          isActive: true,
          description: rateData.description
        }
      });
    }

    const updatedRates = await prisma.pricingRate.findMany({
      where: { isActive: true },
      orderBy: { serviceType: 'asc' }
    });

    return NextResponse.json({ 
      message: 'Pricing rates updated successfully',
      rates: updatedRates 
    });
  } catch (error) {
    console.error('Error updating pricing rates:', error);
    return NextResponse.json({ error: 'Failed to update pricing rates' }, { status: 500 });
  }
}
