import { fetchHubPolicy } from "./hubPolicyService";

export interface TermsOfUseSection {
  heading?: string;
  effectiveDate?: string;
  content?: string;
}

export interface TermsOfUseContent {
  termsOfUse?: TermsOfUseSection;
  // Some franchisees may store content under a generic key — accept both.
  privacyPolicy?: TermsOfUseSection;
}

export interface TermsOfUsePageData {
  id: string;
  franchisee_id: string | null;
  is_global: boolean;
  title: string;
  slug: string;
  template_id: string;
  content: TermsOfUseContent;
  translated_content?: TermsOfUseContent;
  status: string;
  seo_title?: string | null;
  seo_description?: string | null;
  version?: number;
  effective_language?: string;
}

export interface TermsOfUseDataWithTranslations {
  default: TermsOfUseContent;
  translated?: TermsOfUseContent;
  version: number;
  language_code: string;
}

const DEFAULTS: TermsOfUseSection = {
  heading: "Terms of Use",
  effectiveDate: "",
  content: "Terms of Use content is not available at this time. Please contact us for more information.",
};

export class TermsOfUseService {

  /**
   * Signature is unchanged so every caller (the policy page, the registration
   * form's popup, PolicyAgreement) keeps working untouched, but the copy now
   * comes from the hub rather than this franchisee's CMS page. The domain,
   * franchiseeId and language arguments no longer select anything: one
   * published policy serves every licensee, and the hub publishes English only
   * - it ignores a lang parameter. The franchisee `pages/{slug}` endpoint had
   * no translations for these documents either, so nothing is lost.
   */
  async fetchByDomain(
    _domain: string,
    _franchiseeId?: string | null,
    _language?: string | null,
  ): Promise<TermsOfUseDataWithTranslations> {
    const policy = await fetchHubPolicy("tou");

    if (!policy) return this.getDefaultData();

    return {
      default: {
        termsOfUse: {
          heading: policy.title || DEFAULTS.heading,
          // Lifted out of the hub body's preamble, which is stripped from
          // the copy - so the date shows once, in the hero, instead of again
          // as the first line of the text.
          effectiveDate: policy.effectiveDate,
          content: policy.body,
        },
      },
      translated: undefined,
      version: policy.version,
      language_code: "en",
    };
  }

  private async getDefaultData(): Promise<TermsOfUseDataWithTranslations> {
    return {
      default: { termsOfUse: DEFAULTS },
      translated: undefined,
      version: 1,
      language_code: 'en',
    };
  }
}

export const termsOfUseService = new TermsOfUseService();
