import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  listOpportunityFollowups,
  softDeleteOpportunityFollowup,
  updateOpportunityFollowup
} from '@/features/crm/opportunities/server/service';
import { opportunityFollowupSchema } from '@/features/crm/opportunities/schemas/opportunity.schema';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const followupRequestSchema = opportunityFollowupSchema.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.crmOpportunityFollowupUpdate
    });
    const payload = followupRequestSchema.parse(await request.json());
    const accessContext = {
      organizationId: organization.id,
      userId: session.user.id,
      membershipRole: membership.role,
      businessRole: membership.businessRole,
      branchScopeIds: membership.branchScopeIds ?? [],
      productTypeScopeIds: membership.productTypeScopeIds ?? [],
      ownershipScope: membership.ownershipScope ?? 'organization',
      branchScopeMode: membership.branchScopeMode === 'assigned' ? 'assigned' : 'all',
      productScopeMode: membership.productScopeMode === 'assigned' ? 'assigned' : 'all'
    };
    const before = (
      await listOpportunityFollowups(id, organization.id, accessContext)
    ).find(
      (item) => item.id === followupId
    );

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

    const updated = await updateOpportunityFollowup(
      id,
      followupId,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

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

    return NextResponse.json({
      success: true,
      message: 'Opportunity 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 opportunity 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.crmOpportunityFollowupDelete
    });
    const accessContext = {
      organizationId: organization.id,
      userId: session.user.id,
      membershipRole: membership.role,
      businessRole: membership.businessRole,
      branchScopeIds: membership.branchScopeIds ?? [],
      productTypeScopeIds: membership.productTypeScopeIds ?? [],
      ownershipScope: membership.ownershipScope ?? 'organization',
      branchScopeMode: membership.branchScopeMode === 'assigned' ? 'assigned' : 'all',
      productScopeMode: membership.productScopeMode === 'assigned' ? 'assigned' : 'all'
    };
    const before = (
      await listOpportunityFollowups(id, organization.id, accessContext)
    ).find(
      (item) => item.id === followupId
    );

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

    const updated = await softDeleteOpportunityFollowup(
      id,
      followupId,
      organization.id,
      session.user.id,
      accessContext
    );

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

    return NextResponse.json({
      success: true,
      message: 'Opportunity 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 opportunity follow-up' }, { status: 500 });
  }
}

