import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditCreate } from '@/features/foundation/audit-log/service';
import {
  createOpportunityFollowup,
  listOpportunityFollowups
} 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 }>;
};

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

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmOpportunityFollowupRead
    });
    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 items = await listOpportunityFollowups(id, organization.id, accessContext);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Opportunity follow-ups loaded successfully',
      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 opportunity follow-ups' }, { status: 500 });
  }
}

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmOpportunityFollowupCreate
    });
    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 created = await createOpportunityFollowup(
      id,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

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

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

