import { Injectable, computed, inject } from '@angular/core';
import { BootstrapConfig } from '../../../shared/models/config';
import { ContentPageService } from '../services/content-page.service';
import { ContentPage } from '../models/content-page.model';
import { LEGAL_PAGE_DEFINITIONS, LegalPageDefinition, matchesLegalDefinition } from '../models/legal-pages.model';

export interface ContentHealthLegalStatus {
  def: LegalPageDefinition;
  page: ContentPage | null;
}

export type ContentRecommendationKind = 'createLegal' | 'fixSeo' | 'publish' | 'addTitles' | 'none';

export interface ContentRecommendation {
  kind: ContentRecommendationKind;
  labelKey: string;
  pageId?: string;
}

export interface ContentHealth {
  total: number;
  published: number;
  draft: number;
  legalStatus: ContentHealthLegalStatus[];
  missingRequiredLegal: LegalPageDefinition[];
  seoConfiguredCount: number;
  seoHealthPercent: number;
  completionPercent: number;
  lastEditedAt: string | null;
  recommendation: ContentRecommendation;
}

@Injectable({ providedIn: 'root' })
export class ContentManagementFacade {
  private readonly service = inject(ContentPageService);

  pages(bootstrap: BootstrapConfig | null) {
    return bootstrap ? this.service.normalizePages(bootstrap.staticPages) : [];
  }

  hasSeoContent(page: ContentPage): boolean {
    const seoBlocks = [page.seo, ...Object.values(page.translations).map(t => t.seo)].filter((seo): seo is NonNullable<typeof seo> => !!seo);
    return seoBlocks.some(seo => !!(seo.title?.trim() || seo.description?.trim()));
  }

  contentHealth(bootstrap: BootstrapConfig | null): ContentHealth {
    const pages = this.pages(bootstrap);
    const validation = this.validatePages(bootstrap);

    const legalStatus: ContentHealthLegalStatus[] = LEGAL_PAGE_DEFINITIONS.map(def => ({
      def,
      page: pages.find(page => matchesLegalDefinition(page, def)) ?? null,
    }));
    const missingRequiredLegal = legalStatus.filter(status => status.def.required && !status.page).map(status => status.def);

    const seoConfiguredCount = pages.filter(page => this.hasSeoContent(page)).length;
    const seoHealthPercent = pages.length > 0 ? Math.round((seoConfiguredCount / pages.length) * 100) : 0;

    const legalWeight = LEGAL_PAGE_DEFINITIONS.length > 0 ? (legalStatus.filter(s => s.page).length / LEGAL_PAGE_DEFINITIONS.length) * 60 : 0;
    const seoWeight = pages.length > 0 ? (seoConfiguredCount / pages.length) * 40 : 0;
    const completionPercent = Math.round(legalWeight + seoWeight);

    const lastEditedAt = pages.reduce<string | null>((latest, page) => {
      if (!page.updatedAt) {
        return latest;
      }
      return !latest || page.updatedAt > latest ? page.updatedAt : latest;
    }, null);

    const published = pages.filter(page => page.status === 'published').length;
    const draft = pages.filter(page => page.status === 'draft').length;

    let recommendation: ContentRecommendation;
    const firstMissingLegal = missingRequiredLegal[0];
    const firstInvalidSeoId = validation.invalidSeo[0];
    const firstEmptyTitleId = validation.emptyTitles[0];
    const firstDraftLegal = legalStatus.find(status => status.def.required && status.page?.status === 'draft')?.page;

    if (firstMissingLegal) {
      recommendation = { kind: 'createLegal', labelKey: firstMissingLegal.labelKey };
    } else if (firstEmptyTitleId) {
      recommendation = { kind: 'addTitles', labelKey: 'contentManagement.recommendAddTitles', pageId: firstEmptyTitleId };
    } else if (firstInvalidSeoId) {
      recommendation = { kind: 'fixSeo', labelKey: 'contentManagement.recommendFixSeo', pageId: firstInvalidSeoId };
    } else if (firstDraftLegal) {
      recommendation = { kind: 'publish', labelKey: 'contentManagement.recommendPublish', pageId: firstDraftLegal.id };
    } else {
      recommendation = { kind: 'none', labelKey: 'contentManagement.recommendNone' };
    }

    return {
      total: pages.length,
      published,
      draft,
      legalStatus,
      missingRequiredLegal,
      seoConfiguredCount,
      seoHealthPercent,
      completionPercent,
      lastEditedAt,
      recommendation,
    };
  }

  resolvePage(bootstrap: BootstrapConfig, keyOrSlug: string, locale: string) {
    return this.service.resolvePage(bootstrap, keyOrSlug, locale);
  }

  validatePages(bootstrap: BootstrapConfig | null) {
    return this.service.validatePages(this.pages(bootstrap));
  }

  toBootstrapRecord(bootstrap: BootstrapConfig | null) {
    return bootstrap ? this.service.toBootstrapRecord(this.pages(bootstrap)) : {};
  }

  serializePages(pages: ContentPage[]) {
    return this.service.toBootstrapRecord(pages);
  }

  normalizeSlug(value: string): string {
    return this.service.normalizeSlug(value);
  }
}
