import { Injectable, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { AdminAuthService } from '@marketplaces/auth';
import { AdminUsersLocalGateway } from '../../features/admin/users/services/admin-users-local.gateway';

/**
 * UI-only permission gate for the live Telegram/QR admin auth (Mechanism A),
 * which carries no role claim of its own (see admin-auth.service.ts). This
 * derives a permission set by matching the signed-in Telegram username
 * against the mock Users domain's roleId - the same local-only stand-in the
 * rest of the Users admin domain already uses (see BACKEND-API-REFERENCE.md
 * §8 "Users - MOCK-ONLY, no seam"). It is cosmetic until a real backend
 * ships either an admin-role claim on the session, or Mechanism B
 * (Ed25519 JWT + PermissionService) goes live.
 */
@Injectable({ providedIn: 'root' })
export class AdminPermissionsService {
  private readonly adminAuth = inject(AdminAuthService);
  private readonly usersGateway = inject(AdminUsersLocalGateway);

  private readonly users = toSignal(this.usersGateway.loadUsers(), { initialValue: [] });
  private readonly roles = toSignal(this.usersGateway.loadRoles(), { initialValue: [] });

  readonly permissions = computed<readonly string[]>(() => {
    const session = this.adminAuth.session();
    if (!session) {
      return [];
    }
    const username = session.username?.replace(/^@/, '');
    const matchedUser = this.users().find(user => user.telegramUsername.replace(/^@/, '') === username);
    if (!matchedUser) {
      return [];
    }
    return this.roles().find(role => role.id === matchedUser.roleId)?.permissions ?? [];
  });

  has(permission: string): boolean {
    const permissions = this.permissions();
    return permissions.includes('*') || permissions.includes(permission);
  }
}
