import type {
  CrmApprovalAuthority,
  CrmEffectiveScopeMode,
  CrmOwnershipScope,
  CrmRoleAssignmentScopeMode,
  Permission
} from '@/lib/auth/rbac';

export interface UserOrganization {
  id: string;
  name: string;
  role: 'admin' | 'user';
}

export interface UserMembership {
  organizationId: string;
  organizationName: string;
  membershipRole: 'admin' | 'user';
  businessRole: string;
  isLegacyBusinessRoleDeprecated?: boolean;
}

export interface UserCrmRoleAssignment {
  id: string;
  organizationId: string;
  roleProfileId: string;
  roleProfileCode: string;
  roleProfileName: string;
  branchScopeMode: CrmRoleAssignmentScopeMode;
  branchScopeIds: string[];
  productTypeScopeMode: CrmRoleAssignmentScopeMode;
  productTypeScopeIds: string[];
  isPrimary: boolean;
  isActive: boolean;
}

export interface UserCrmAccessSummary {
  organizationId: string;
  organizationName: string;
  primaryCrmRole: string | null;
  primaryCrmRoleLabel: string | null;
  roleCount: number;
  permissions: Permission[];
  ownershipScope: CrmOwnershipScope;
  branchScopeMode: CrmEffectiveScopeMode;
  branchScopeIds: string[];
  productScopeMode: CrmEffectiveScopeMode;
  productTypeScopeIds: string[];
  approvalAuthority: CrmApprovalAuthority;
  usedLegacyFallback: boolean;
}

export interface User {
  id: string;
  name: string;
  email: string;
  systemRole: 'super_admin' | 'user';
  activeMembershipRole: 'admin' | 'user' | null;
  activeOrganizationId: string | null;
  organizations: UserOrganization[];
  memberships: UserMembership[];
  crmRoleAssignments?: UserCrmRoleAssignment[];
  crmAccessSummaries?: UserCrmAccessSummary[];
  primaryCrmRole?: string | null;
  crmRoleCount?: number;
  branchScopeSummary?: string;
  productScopeSummary?: string;
  hasLegacyBusinessRoleFallback?: boolean;
}

export type UserFilters = {
  page?: number;
  limit?: number;
  roles?: string;
  search?: string;
  sort?: string;
};

export type UsersResponse = {
  success: boolean;
  time: string;
  message: string;
  total_users: number;
  offset: number;
  limit: number;
  users: User[];
};

export type UserMutationPayload = {
  name: string;
  email: string;
  password?: string;
  systemRole: 'super_admin' | 'user';
  memberships: Array<{
    organizationId: string;
    membershipRole: 'admin' | 'user';
  }>;
  crmRoleAssignments: Array<{
    id?: string;
    organizationId: string;
    roleProfileId: string;
    branchScopeMode: CrmRoleAssignmentScopeMode;
    branchScopeIds: string[];
    productTypeScopeMode: CrmRoleAssignmentScopeMode;
    productTypeScopeIds: string[];
    isPrimary: boolean;
    isActive: boolean;
  }>;
};
