export type UserRole = "caregiver" | "kitchen" | "admin" | "super-admin";

export interface TenantRole {
  tenant: { id: number; name: string } | number;
  roles?: string[];
}

export interface User {
  id: number;
  email: string;
  name?: string;
  roles?: string[];
  tenants?: TenantRole[];
}

export function getUserRoles(user: User): UserRole[] {
  const roles: UserRole[] = [];

  if (user.roles?.includes("super-admin")) {
    roles.push("super-admin", "admin", "caregiver", "kitchen");
    return roles;
  }

  const tenantRoles = user.tenants?.flatMap((t) => t.roles || []) || [];

  if (tenantRoles.includes("admin")) {
    roles.push("admin", "caregiver", "kitchen");
  }
  if (tenantRoles.includes("caregiver") && !roles.includes("caregiver")) {
    roles.push("caregiver");
  }
  if (tenantRoles.includes("kitchen") && !roles.includes("kitchen")) {
    roles.push("kitchen");
  }

  return roles;
}

export function hasRole(user: User, role: UserRole): boolean {
  return getUserRoles(user).includes(role);
}

export function getPrimaryRole(user: User): UserRole | null {
  if (user.roles?.includes("super-admin")) {
    return "admin";
  }

  const tenantRoles = user.tenants?.flatMap((t) => t.roles || []) || [];

  if (tenantRoles.includes("admin")) {
    return "admin";
  }
  if (tenantRoles.includes("kitchen")) {
    return "kitchen";
  }
  if (tenantRoles.includes("caregiver")) {
    return "caregiver";
  }

  return null;
}

export function getRedirectPath(role: UserRole | null): string {
  switch (role) {
    case "kitchen":
      return "/kitchen/dashboard";
    case "caregiver":
    case "admin":
    case "super-admin":
      return "/caregiver/dashboard";
    default:
      return "/login";
  }
}

export function getTenantName(user: User): string {
  const firstTenant = user.tenants?.[0]?.tenant;
  if (firstTenant && typeof firstTenant === "object") {
    return firstTenant.name;
  }
  return "Care Home";
}
