// app/(lib)/services/privacyPolicyService.ts
import { fetchHubPolicy } from "./hubPolicyService";

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

export interface PrivacyPolicyContent {
  privacyPolicy?: PrivacyPolicySection;
}

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

export interface PrivacyPolicyDataWithTranslations {
  default: PrivacyPolicyContent;
  translated?: PrivacyPolicyContent;
  version: number;
  language_code: string;
}

const DEFAULTS: PrivacyPolicySection = {
  heading: "Privacy Policy",
  effectiveDate: "",
  content: "Privacy policy content is not available at this time. Please contact us for more information.",
};

export class PrivacyPolicyService {

  /**
   * 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<PrivacyPolicyDataWithTranslations> {
    const policy = await fetchHubPolicy("privacy");

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

    return {
      default: {
        privacyPolicy: {
          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<PrivacyPolicyDataWithTranslations> {
    return {
      default: { privacyPolicy: DEFAULTS },
      translated: undefined,
      version: 1,
      language_code: 'en',
    };
  }
}

export const privacyPolicyService = new PrivacyPolicyService();
