import { Injectable, inject, signal, computed } from '@angular/core';
import { Store } from '@ngrx/store';
import { selectUser } from '../store';
import { Branch } from '../models/auth.model';

@Injectable({ providedIn: 'root' })
export class BranchContextService {
  private store = inject(Store);

  /** All branches the current user has access to */
  userBranches = signal<Branch[]>([]);

  /** IDs of branches the user has access to */
  userBranchIds = computed(() => this.userBranches().map(b => b.id));

  /** Whether the user has branch restrictions */
  hasBranchRestriction = computed(() => this.userBranches().length > 0);

  constructor() {
    this.store.select(selectUser).subscribe(user => {
      this.userBranches.set(user?.branches || []);
    });
  }

  /** Check if a warehouse belongs to the user's branches (by branch_id). Shared warehouses (null branch_id) are always allowed. */
  isWarehouseAllowed(warehouseBranchId: number | null): boolean {
    if (!this.hasBranchRestriction()) return true;
    if (!warehouseBranchId) return true; // shared warehouse
    return this.userBranchIds().includes(warehouseBranchId);
  }
}
