import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate } from '@/features/foundation/audit-log/service';
import { createEnquiry, listEnquiries } from '@/features/crm/enquiries/server/service';
import { enquirySchema } from '@/features/crm/enquiries/schemas/enquiry.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const enquiryRequestSchema = enquirySchema.extend({
  contactId: z.string().nullable().optional(),
  branchId: z.string().nullable().optional(),
  leadChannel: z.string().nullable().optional(),
  expectedCloseDate: z.string().nullable().optional()
});

export async function GET(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmEnquiryRead
    });
    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 pipelineStage = searchParams.get('pipelineStage') ?? undefined;
    const status = searchParams.get('status') ?? undefined;
    const productType = searchParams.get('productType') ?? undefined;
    const priority = searchParams.get('priority') ?? undefined;
    const branch = searchParams.get('branch') ?? undefined;
    const customer = searchParams.get('customer') ?? undefined;
    const sort = searchParams.get('sort') ?? undefined;
    const result = await listEnquiries(
      {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole
      },
      {
        page,
        limit,
        search,
        pipelineStage: pipelineStage as 'lead' | 'enquiry' | 'closed_won' | 'closed_lost' | undefined,
        status,
        productType,
        priority,
        branch,
        customer,
        sort
      }
    );
    const offset = (page - 1) * limit;

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Enquiries 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 enquiries' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmEnquiryCreate
    });
    const payload = enquiryRequestSchema.parse(await request.json());
    const created = await createEnquiry(
      organization.id,
      session.user.id,
      membership.businessRole,
      payload
    );

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

    return NextResponse.json(
      {
        success: true,
        message: 'Enquiry created successfully',
        enquiry: 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 enquiry' }, { status: 500 });
  }
}
