import { Injectable, inject } from '@angular/core';
import { RoleId } from '../../models/role.model';
import { Team } from '../../models/team.model';
import { TeamPermissionAction } from '../../models/team-permissions.model';
import { AuthStore } from '../auth/auth-store';

const ACTION_TO_SETTING_KEY: Record<TeamPermissionAction, string> = {
  transactionCreate: 'transaction_create_min_role',
  transactionReverse: 'transaction_reverse_min_role',
  invite: 'invite_min_role',
  memberManage: 'member_manage_min_role',
  penaltyManage: 'penalty_manage_min_role',
  publicAccessManage: 'public_access_manage_min_role',
};

const DEFAULT_MIN_ROLE: Record<TeamPermissionAction, number> = {
  transactionCreate: 2,
  transactionReverse: 2,
  invite: 3,
  memberManage: 3,
  penaltyManage: 3,
  publicAccessManage: 3,
};

@Injectable({ providedIn: 'root' })
export class TeamPermissionsService {
  private readonly authStore = inject(AuthStore);

  canDo(team: Team | null | undefined, action: TeamPermissionAction): boolean {
    const user = this.authStore.currentUser();
    if (!user) return false;
    if (user.role?.id === RoleId.Admin) return true;

    const minRole = this.minRoleFor(team, action);
    return (
      team?.players?.some(
        (player) =>
          player.active && player.user?.id === user.id && (player.teamRole?.id ?? 0) >= minRole,
      ) ?? false
    );
  }

  private minRoleFor(team: Team | null | undefined, action: TeamPermissionAction): number {
    const key = ACTION_TO_SETTING_KEY[action];
    const setting = team?.settings?.find((s) => s.key === key);
    const parsed = setting ? Number(setting.value) : NaN;
    return Number.isInteger(parsed) && parsed >= 1 && parsed <= 5 ? parsed : DEFAULT_MIN_ROLE[action];
  }
}
