import { fetchHubPolicy } from "./hubPolicyService";

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

export interface CookiePolicyContent {
  cookiePolicy?: CookiePolicySection;
}

export interface CookiePolicyDataWithTranslations {
  default: CookiePolicyContent;
  translated?: CookiePolicyContent;
  version: number;
  language_code: string;
}

const DEFAULTS: CookiePolicySection = {
  heading: "Cookie Notice",
  effectiveDate: "",
  content:
    "Cookie notice content is not available at this time. Please contact us for more information.",
};

/**
 * The Cookie Notice, from the same hub source as the Privacy Policy and Terms
 * of Use. The hub has published it all along (`type=cookies`, page_url
 * `cookie-policy`) but the site had no page rendering it, so the notice was
 * unreachable - it explains what the site stores on a visitor's device, which
 * is exactly what someone following a footer link expects to find.
 */
export class CookiePolicyService {
  /**
   * Signature matches the other two policy services so the action layer and
   * PolicyPageClient work unchanged. The arguments select nothing: one
   * published notice serves every licensee, and the hub publishes English only.
   */
  async fetchByDomain(
    _domain: string,
    _franchiseeId?: string | null,
    _language?: string | null,
  ): Promise<CookiePolicyDataWithTranslations> {
    const policy = await fetchHubPolicy("cookies");

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

    return {
      default: {
        cookiePolicy: {
          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, rather than 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<CookiePolicyDataWithTranslations> {
    return {
      default: { cookiePolicy: DEFAULTS },
      translated: undefined,
      version: 1,
      language_code: "en",
    };
  }
}

export const cookiePolicyService = new CookiePolicyService();
