import { Injectable, inject, signal } from '@angular/core';
import { Observable, of, tap } from 'rxjs';
import { MenuContext } from '../../models/context/context.model';
import { SAAS_MENU_DATA } from './menu.data';
import { Menu } from '../../../core/services/common/nav.service';
import { TokenStorageService } from '../auth/token-storage.service';

@Injectable({ providedIn: 'root' })
export class MenuService {
  private readonly tokenStorage = inject(TokenStorageService);
  readonly menuContext = signal<MenuContext | null>(null);

  loadMenu(): Observable<MenuContext> {
    const context = this.cloneMenuContext(SAAS_MENU_DATA);
    context.items = this.filterAuthorizedItems(context.items);
    return of(context).pipe(
      tap((menuContext) => {
        this.menuContext.set(menuContext);
      })
    );
  }

  getNavigationMenu(): Menu[] {
    return this.cloneMenuItems(this.menuContext()?.items ?? []);
  }

  getDefaultLandingPage(): string | null {
    return this.menuContext()?.defaultLandingPage ?? null;
  }

  clear(): void {
    this.menuContext.set(null);
  }

  private cloneMenuContext(context: MenuContext): MenuContext {
    return {
      defaultLandingPage: context.defaultLandingPage,
      items: this.cloneMenuItems(context.items),
    };
  }

  private cloneMenuItems(items: Menu[]): Menu[] {
    return JSON.parse(JSON.stringify(items)) as Menu[];
  }

  private filterAuthorizedItems(items: Menu[]): Menu[] {
    const isSuperAdmin = (this.tokenStorage.getUser()?.roles ?? []).includes('super_admin');
    return items
      .filter(item => isSuperAdmin || item.path !== '/users')
      .map(item => ({
        ...item,
        children: item.children ? this.filterAuthorizedItems(item.children) : item.children,
        children2: item.children2 ? this.filterAuthorizedItems(item.children2) : item.children2
      }));
  }
}
