import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { ConfigService } from '../../core/config/config.service';
import { PageConfig } from '../../shared/models/config';

@Injectable({ providedIn: 'root' })
export class PageResolverService {
  constructor(private readonly configService: ConfigService) {}

  resolveByUrl(url: string): Observable<PageConfig | null> {
    const pagePath = this.toPagePath(url);

    return this.configService.loadBootstrap().pipe(
      map((bootstrap) => {
        return (
          bootstrap.pages.find((page) => {
            if (page.visible === false) {
              return false;
            }

            return this.normalizePath(page.route.path) === pagePath;
          }) ?? null
        );
      })
    );
  }

  private toPagePath(url: string): string {
    const noHash = url.split('#')[0];
    const noQuery = noHash.split('?')[0];
    const segments = noQuery.split('/').filter(Boolean);
    const withoutLang = segments.length > 0 ? segments.slice(1) : [];

    if (withoutLang.length === 0) {
      return '/';
    }

    return this.normalizePath(`/${withoutLang.join('/')}`);
  }

  private normalizePath(path: string): string {
    const trimmed = path.trim();
    if (!trimmed || trimmed === '/') {
      return '/';
    }

    return `/${trimmed.replace(/^\/+/, '').replace(/\/+$/, '')}`;
  }
}
