import { Injectable } from '@nestjs/common';

const MANAGER_PLUS = ['super_admin', 'club_admin', 'manager'];

@Injectable()
export class BookingPermissions {
  /**
   * Filter records by role: trainers see only their own bookings.
   */
  filterRecordsByRole(userId: string, role: string): Record<string, any> {
    const roles = normalizeRoles(role);
    if (hasAnyRole(roles, MANAGER_PLUS)) return {};
    if (hasAnyRole(roles, ['trainer'])) return { staffId: userId };
    if (hasAnyRole(roles, ['coordinator'])) return {};
    if (hasAnyRole(roles, ['receptionist'])) return {};
    return { staffId: userId };
  }

  canCreateRecord(role: string): boolean {
    return hasAnyRole(normalizeRoles(role), [...MANAGER_PLUS, 'receptionist']);
  }

  canUpdateRecord(userId: string, role: string, record: { staffId: string }): boolean {
    const roles = normalizeRoles(role);
    if (hasAnyRole(roles, MANAGER_PLUS)) return true;
    if (hasAnyRole(roles, ['trainer'])) return record.staffId === userId;
    return false;
  }

  canDeleteRecord(role: string): boolean {
    return hasAnyRole(normalizeRoles(role), MANAGER_PLUS);
  }

  canManageGroupEvents(role: string): boolean {
    return hasAnyRole(normalizeRoles(role), MANAGER_PLUS);
  }

  canMarkAttendance(userId: string, role: string, record: { staffId: string }): boolean {
    const roles = normalizeRoles(role);
    if (hasAnyRole(roles, MANAGER_PLUS)) return true;
    if (hasAnyRole(roles, ['trainer'])) return record.staffId === userId;
    return false;
  }

  filterGroupEventsByRole(userId: string, role: string): Record<string, any> {
    const roles = normalizeRoles(role);
    if (hasAnyRole(roles, MANAGER_PLUS)) return {};
    if (hasAnyRole(roles, ['trainer'])) return { staffId: userId };
    return {};
  }
}

function normalizeRoles(role: string | string[]): string[] {
  if (Array.isArray(role)) return role.map((r) => r.toLowerCase());
  return [role.toLowerCase()];
}

function hasAnyRole(userRoles: string[], allowed: string[]): boolean {
  return userRoles.some((r) => allowed.includes(r));
}
