import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  deleteCrmUserRoleAssignment,
  updateCrmUserRoleAssignment
} from '@/features/foundation/crm-role-assignments/server/service';
import { PERMISSIONS, ROLE_ASSIGNMENT_SCOPE_MODES } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const updateAssignmentSchema = z.object({
  branchScopeMode: z.enum(ROLE_ASSIGNMENT_SCOPE_MODES),
  branchScopeIds: z.array(z.string()).default([]),
  productTypeScopeMode: z.enum(ROLE_ASSIGNMENT_SCOPE_MODES),
  productTypeScopeIds: z.array(z.string()).default([]),
  isPrimary: z.boolean(),
  isActive: z.boolean()
});

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

export async function PATCH(request: NextRequest, props: RouteProps) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmUserRoleAssignmentManage
    });
    const payload = updateAssignmentSchema.parse(await request.json());
    const { id } = await props.params;
    const assignment = await updateCrmUserRoleAssignment(
      organization.id,
      session.user.id,
      id,
      payload
    );

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

export async function DELETE(_request: NextRequest, props: RouteProps) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmUserRoleAssignmentManage
    });
    const { id } = await props.params;
    await deleteCrmUserRoleAssignment(organization.id, session.user.id, id);

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