import { Injectable, computed, signal } from '@angular/core';

const T = 'bms_staff_token';
const U = 'bms_staff_user';
const P = 'bms_staff_perms';

export interface StaffUser { id: number; name: string; username: string; business_id: number; }

@Injectable({ providedIn: 'root' })
export class AuthService {
  readonly token = signal<string | null>(localStorage.getItem(T));
  readonly user = signal<StaffUser | null>(JSON.parse(localStorage.getItem(U) || 'null'));
  readonly perms = signal<string[]>(JSON.parse(localStorage.getItem(P) || '[]'));
  readonly isAuthed = computed(() => !!this.token());

  set(token: string, user: StaffUser, perms: string[] = []): void {
    this.token.set(token);
    this.user.set(user);
    this.perms.set(perms);
    localStorage.setItem(T, token);
    localStorage.setItem(U, JSON.stringify(user));
    localStorage.setItem(P, JSON.stringify(perms));
  }

  /** Does the signed-in user hold this BMS ability? (empty perms = allow, for legacy tokens) */
  can(perm: string): boolean {
    const p = this.perms();
    return p.length === 0 || p.includes(perm);
  }

  clear(): void {
    this.token.set(null);
    this.user.set(null);
    this.perms.set([]);
    localStorage.removeItem(T);
    localStorage.removeItem(U);
    localStorage.removeItem(P);
  }
}
