import { Injectable, signal } from '@angular/core';
import { Observable, of, tap } from 'rxjs';
import { MenuContext } from '../models/context.model';
import { SAAS_MENU_DATA } from './menu.data';
import { Menu } from '../../shared/services/nav.service';

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

  loadMenu(): Observable<MenuContext> {
    const context = this.cloneMenuContext(SAAS_MENU_DATA);
    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[];
  }
}