import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditDelete, auditUpdate } from '@/features/foundation/audit-log/service';
import {
  getOpportunityActivity,
  getOpportunityDetail,
  softDeleteOpportunity,
  updateOpportunity
} from '@/features/crm/opportunities/server/service';
import { opportunitySchema } 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 opportunityRequestSchema = opportunitySchema.extend({
contactId: z.string().nullable().optional(),
branchId: z.string().nullable().optional(),
leadChannel: z.string().nullable().optional(),
expectedCloseDate: z.string().nullable().optional(),
projectCloseDate: z.string().nullable().optional(),
deliveryDate: 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.crmOpportunityRead
    });
    const accessContext = {
      organizationId: organization.id,
      userId: session.user.id,
      membershipRole: membership.role,
      businessRole: membership.businessRole,
      permissions: membership.permissions ?? [],
      branchScopeIds: membership.branchScopeIds ?? [],
      productTypeScopeIds: membership.productTypeScopeIds ?? [],
      ownershipScope: membership.ownershipScope ?? 'organization',
      branchScopeMode: membership.branchScopeMode === 'assigned' ? 'assigned' : 'all',
      productScopeMode: membership.productScopeMode === 'assigned' ? 'assigned' : 'all'
    };
    const [opportunity, activity] = await Promise.all([
      getOpportunityDetail(id, organization.id, accessContext),
      getOpportunityActivity(id, organization.id, accessContext)
    ]);

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

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmOpportunityUpdate
    });
    const payload = opportunityRequestSchema.parse(await request.json());
    const accessContext = {
      organizationId: organization.id,
      userId: session.user.id,
      membershipRole: membership.role,
      businessRole: membership.businessRole,
      permissions: membership.permissions ?? [],
      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 getOpportunityDetail(id, organization.id, accessContext);
    const updated = await updateOpportunity(id, organization.id, session.user.id, payload, accessContext);

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

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

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmOpportunityDelete
    });
    const accessContext = {
      organizationId: organization.id,
      userId: session.user.id,
      membershipRole: membership.role,
      businessRole: membership.businessRole,
      permissions: membership.permissions ?? [],
      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 getOpportunityDetail(id, organization.id, accessContext);
    const updated = await softDeleteOpportunity(id, organization.id, session.user.id, accessContext);

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

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