import { Injectable, inject, Injector } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { RouterStateSnapshot, TitleStrategy } from '@angular/router';
import { TabService } from '@isa/core/tabs';
import { TITLE_PREFIX } from './title-prefix';

/**
 * Custom TitleStrategy for the ISA application that:
 * 1. Automatically adds the ISA prefix from config to all page titles
 * 2. Updates the TabService with the page title for tab management
 * 3. Sets the browser document title
 *
 * @example
 * ```typescript
 * // In app.module.ts or app.config.ts
 * import { TitleStrategy } from '@angular/router';
 * import { IsaTitleStrategy } from '@isa/common/title-management';
 *
 * @NgModule({
 *   providers: [
 *     { provide: TitleStrategy, useClass: IsaTitleStrategy }
 *   ]
 * })
 * export class AppModule {}
 * ```
 *
 * @example
 * ```typescript
 * // Usage in routes
 * const routes: Routes = [
 *   {
 *     path: 'dashboard',
 *     component: DashboardComponent,
 *     title: 'Dashboard' // Will become "ISA - Dashboard"
 *   },
 *   {
 *     path: 'search',
 *     component: SearchComponent,
 *     title: 'Artikelsuche' // Will become "ISA - Artikelsuche"
 *   }
 * ];
 * ```
 */
@Injectable({ providedIn: 'root' })
export class IsaTitleStrategy extends TitleStrategy {
  readonly #title = inject(Title);
  readonly #injector = inject(Injector);
  readonly #titlePrefix = inject(TITLE_PREFIX);

  // Lazy injection to avoid circular dependency:
  // TitleStrategy → TabService → UserStorageProvider → AuthService → Router → TitleStrategy
  #getTabService() {
    return this.#injector.get(TabService);
  }

  /**
   * Updates the page title when navigation occurs.
   * This method is called automatically by Angular's Router.
   *
   * @param snapshot - The router state snapshot containing route data
   */
  override updateTitle(snapshot: RouterStateSnapshot): void {
    const pageTitle = this.buildTitle(snapshot);

    if (pageTitle) {
      this.#updateTitleAndTab(pageTitle);
    }
  }

  /**
   * Updates both the document title and the tab name with the given page title.
   *
   * @param pageTitle - The page title to set (without prefix)
   * @private
   */
  #updateTitleAndTab(pageTitle: string): void {
    const fullTitle = `${this.#titlePrefix} - ${pageTitle}`;

    this.#title.setTitle(fullTitle);

    const tabService = this.#getTabService();
    const activeTabId = tabService.activatedTabId();
    if (activeTabId !== null) {
      tabService.patchTab(activeTabId, {
        name: pageTitle,
      });
    }
  }
}
