import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate } from '@/features/foundation/audit-log/service';
import { createQuotation, listQuotations } from '@/features/crm/quotations/server/service';
import { quotationSchema } from '@/features/crm/quotations/schemas/quotation.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationRead
    });
    const { searchParams } = request.nextUrl;
    const page = Number(searchParams.get('page') ?? 1);
    const limit = Number(searchParams.get('limit') ?? 10);
    const search = searchParams.get('search') ?? undefined;
    const status = searchParams.get('status') ?? undefined;
    const quotationType = searchParams.get('quotationType') ?? undefined;
    const branch = searchParams.get('branch') ?? undefined;
    const customer = searchParams.get('customer') ?? undefined;
    const enquiry = searchParams.get('enquiry') ?? undefined;
    const hot = searchParams.get('hot') ?? undefined;
    const sort = searchParams.get('sort') ?? undefined;
    const result = await listQuotations(organization.id, {
      page,
      limit,
      search,
      status,
      quotationType,
      branch,
      customer,
      enquiry,
      hot,
      sort
    });
    const offset = (page - 1) * limit;

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Quotations loaded successfully',
      totalItems: result.totalItems,
      offset,
      limit,
      items: result.items
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to load quotations' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationCreate
    });
    const payload = quotationSchema.parse(await request.json());
    const created = await createQuotation(organization.id, session.user.id, payload);

    await auditCreate({
      organizationId: organization.id,
      branchId: created.branchId,
      userId: session.user.id,
      entityType: 'crm_quotation',
      entityId: created.id,
      afterData: created
    });

    return NextResponse.json(
      {
        success: true,
        message: 'Quotation created successfully',
        quotation: created
      },
      { status: 201 }
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to create quotation' }, { status: 500 });
  }
}
