import {MembershipRole, PlatformRole, SessionMembership} from "@/features/auth/types";

export type Permission =
  | "tenant:create"
  | "tenant:update"
  | "tenant:suspend"
  | "tenant:view:any"
  | "analytics:view:platform"
  | "platform-settings:update"
  | "audit:view:any"
  | "vehicle:create"
  | "vehicle:read"
  | "vehicle:read:public"
  | "vehicle:update"
  | "vehicle:update-status"
  | "vehicle:archive"
  | "booking:create"
  | "booking:create:self"
  | "booking:read"
  | "booking:read:self"
  | "booking:update"
  | "booking:update-status"
  | "booking:confirm"
  | "booking:cancel"
  | "booking:cancel:self"
  | "booking:complete"
  | "customer:read"
  | "customer:update"
  | "customer:update-basic"
  | "customer:blacklist"
  | "invoice:create"
  | "invoice:read"
  | "invoice:update"
  | "payment:read"
  | "staff:invite"
  | "staff:update"
  | "staff:disable"
  | "tenant-settings:update"
  | "profile:update:self"
  | "document:upload:self";

type PermissionContext = {
  platformRole: PlatformRole;
  membership?: SessionMembership | null;
};

const rolePermissions: Record<MembershipRole, Set<Permission>> = {
  COMPANY_ADMIN: new Set([
    "vehicle:create",
    "vehicle:read",
    "vehicle:update",
    "vehicle:archive",
    "booking:create",
    "booking:read",
    "booking:update",
    "booking:confirm",
    "booking:cancel",
    "booking:complete",
    "customer:read",
    "customer:update",
    "customer:blacklist",
    "invoice:create",
    "invoice:read",
    "invoice:update",
    "staff:invite",
    "staff:update",
    "staff:disable",
    "tenant-settings:update"
  ]),
  COMPANY_STAFF: new Set([
    "vehicle:read",
    "vehicle:update-status",
    "booking:create",
    "booking:read",
    "booking:update-status",
    "customer:read",
    "customer:update-basic",
    "invoice:read",
    "payment:read"
  ]),
  CUSTOMER: new Set([
    "vehicle:read:public",
    "booking:create:self",
    "booking:read:self",
    "booking:cancel:self",
    "profile:update:self",
    "document:upload:self"
  ])
};

const superAdminPermissions = new Set<Permission>([
  "tenant:create",
  "tenant:update",
  "tenant:suspend",
  "tenant:view:any",
  "analytics:view:platform",
  "platform-settings:update",
  "audit:view:any"
]);

export function hasPermission(permission: Permission, context: PermissionContext) {
  if (context.platformRole === "SUPER_ADMIN") {
    return superAdminPermissions.has(permission);
  }

  if (!context.membership) {
    return false;
  }

  return rolePermissions[context.membership.role].has(permission);
}

export function getMembershipForTenant(memberships: SessionMembership[], tenantId?: string | null) {
  if (!tenantId) {
    return null;
  }

  return memberships.find((membership) => membership.tenantId === tenantId) ?? null;
}