import {
  GENERATED_ROLE_NAMES,
  GENERATED_ROLE_TO_PRODUCT_ROLE,
  PRODUCT_ROLE_VALUES,
  STAFF_TYPE_TO_PRODUCT_ROLE,
  type ProductRoleValue,
} from './roles';

export const CAMPUS_ATTENDANCE_TENANT_WIDE_ROLE_NAMES = Object.freeze([
  GENERATED_ROLE_NAMES.SUPER_ADMIN,
  GENERATED_ROLE_NAMES.ADMIN,
  GENERATED_ROLE_NAMES.PLATFORM_OWNER,
]);

export const CAMPUS_ATTENDANCE_MANAGER_ROLE_NAMES = Object.freeze([
  ...CAMPUS_ATTENDANCE_TENANT_WIDE_ROLE_NAMES,
  GENERATED_ROLE_NAMES.TENANT_DIRECTOR,
  GENERATED_ROLE_NAMES.CAMPUS_MANAGER,
  GENERATED_ROLE_NAMES.FINANCE_OFFICER,
]);

export const CAMPUS_ATTENDANCE_MANAGE_PRODUCT_ROLES = Object.freeze([
  PRODUCT_ROLE_VALUES.OFFICE,
  PRODUCT_ROLE_VALUES.DIRECTOR,
  PRODUCT_ROLE_VALUES.SUPERINTENDENT,
]);

export const CAMPUS_ATTENDANCE_DEFAULT_LIMIT = 120;
export const CAMPUS_ATTENDANCE_MAX_LIMIT = 366;

interface ProductRoleUser {
  app_role?: { name?: string | null } | null;
  staff_user?: Array<{ staff_type?: string | null }> | null;
}

export function normalizeCampusKey(value: unknown): string | null {
  if (typeof value !== 'string' || value.trim().length === 0) {
    return null;
  }

  const normalized = value.trim().toLowerCase().replace(/\s+campus$/u, '');

  return normalized || null;
}

export function getProductRole(
  currentUser: ProductRoleUser | null | undefined,
): ProductRoleValue {
  const roleName = currentUser?.app_role?.name;
  const staffProfile = Array.isArray(currentUser?.staff_user)
    ? currentUser.staff_user[0]
    : null;

  if (roleName && GENERATED_ROLE_TO_PRODUCT_ROLE[roleName]) {
    return GENERATED_ROLE_TO_PRODUCT_ROLE[roleName];
  }

  if (
    staffProfile?.staff_type &&
    STAFF_TYPE_TO_PRODUCT_ROLE[staffProfile.staff_type]
  ) {
    return STAFF_TYPE_TO_PRODUCT_ROLE[staffProfile.staff_type];
  }

  return PRODUCT_ROLE_VALUES.TEACHER;
}
