import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  listEnquiryFollowups,
  softDeleteEnquiryFollowup,
  updateEnquiryFollowup
} from '@/features/crm/enquiries/server/service';
import { enquiryFollowupSchema } from '@/features/crm/enquiries/schemas/enquiry.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string; followupId: string }>;
};

const followupRequestSchema = enquiryFollowupSchema.extend({
  contactId: z.string().nullable().optional(),
  nextFollowupDate: z.string().nullable().optional()
});

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id, followupId } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmEnquiryFollowupUpdate
    });
    const payload = followupRequestSchema.parse(await request.json());
    const before = (
      await listEnquiryFollowups(id, organization.id, {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole
      })
    ).find(
      (item) => item.id === followupId
    );

    if (!before) {
      return NextResponse.json({ message: 'Follow-up not found' }, { status: 404 });
    }

    const updated = await updateEnquiryFollowup(
      id,
      followupId,
      organization.id,
      session.user.id,
      payload,
      {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole
      }
    );

    await auditUpdate({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_enquiry_followup',
      entityId: followupId,
      beforeData: before,
      afterData: updated
    });

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

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id, followupId } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmEnquiryFollowupDelete
    });
    const before = (
      await listEnquiryFollowups(id, organization.id, {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole
      })
    ).find(
      (item) => item.id === followupId
    );

    if (!before) {
      return NextResponse.json({ message: 'Follow-up not found' }, { status: 404 });
    }

    const updated = await softDeleteEnquiryFollowup(
      id,
      followupId,
      organization.id,
      session.user.id,
      {
        organizationId: organization.id,
        userId: session.user.id,
        membershipRole: membership.role,
        businessRole: membership.businessRole
      }
    );

    await auditDelete({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_enquiry_followup',
      entityId: followupId,
      beforeData: before,
      afterData: updated
    });

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