import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditAction } from '@/features/foundation/audit-log/service';
import {
  listCustomerContactShares,
  shareCustomerContact
} from '@/features/crm/customers/server/service';
import { buildCrmSecurityContext } from '@/features/crm/security/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const shareSchema = z.object({
  sharedToUserId: z.string().min(1, 'Shared user is required'),
  remark: z.string().optional().nullable()
});

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id, contactId } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmContactShareRead
    });
    const accessContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const items = await listCustomerContactShares(
      id,
      contactId,
      organization.id,
      accessContext
    );

    return NextResponse.json({
      success: true,
      message: 'Contact shares loaded successfully',
      items
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('GET /api/crm/customers/[id]/contacts/[contactId]/shares failed', error);
    return NextResponse.json({ message: 'Unable to load contact shares' }, { status: 500 });
  }
}

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id, contactId } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmContactShareCreate
    });
    const payload = shareSchema.parse(await request.json());
    const accessContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const created = await shareCustomerContact(
      id,
      contactId,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_contact_share',
      entityId: created.id,
      action: 'share',
      afterData: {
        customerId: id,
        contactId,
        sharedUser: payload.sharedToUserId,
        remark: payload.remark ?? null
      }
    });

    return NextResponse.json(
      {
        success: true,
        message: 'Contact shared successfully'
      },
      { 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 }
      );
    }

    console.error('POST /api/crm/customers/[id]/contacts/[contactId]/shares failed', error);
    return NextResponse.json({ message: 'Unable to share contact' }, { status: 500 });
  }
}
