import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  createCrmUserRoleAssignment,
  listResolvedCrmRoleAssignments
} 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 assignmentSchema = z.object({
  userId: z.string().min(1),
  roleProfileId: z.string().min(1),
  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()
});

export async function GET() {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmUserRoleAssignmentRead
    });
    const data = await listResolvedCrmRoleAssignments(organization.id, session.user.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'CRM user role assignments loaded successfully',
      ...data
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json(
      { message: 'Unable to load CRM user role assignments' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmUserRoleAssignmentManage
    });
    const payload = assignmentSchema.parse(await request.json());
    const assignment = await createCrmUserRoleAssignment(
      organization.id,
      session.user.id,
      payload
    );

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