import {
  HeaderFooterHomeResponse,
  ProcessedHeaderFooterHomeData,
} from "@/src/lib/types/header";
import { apiClient } from "../../app/api/client";
import { handleAPIError } from "../utils/apiErrorHandler";

export class DomainNotRecognizedError extends Error {
  constructor(message: string = "Domain not recognized") {
    super(message);
    this.name = "DomainNotRecognizedError";
  }
}

export class HeaderFooterService {
  private readonly endpoint = "header-footer/home";

  async fetchByDomain(domain: string, franchiseeId?: string | null): Promise<ProcessedHeaderFooterHomeData> {
    const startTime = Date.now();

    // ✅ DEV / LOCALHOST BYPASS
    if (
      process.env.NODE_ENV === "development" &&
      (domain === "localhost" || domain?.includes("localhost"))
    ) {

      return this.getDefaultData();
    }
    ////////////////////////////////////

    try {
      const params: Record<string, string> = {};
      if (franchiseeId) params.franchiseeId = franchiseeId;

      const response = await apiClient.get<HeaderFooterHomeResponse>(
        this.endpoint,
        {
          headers: { "X-Domain": domain },
          params: Object.keys(params).length > 0 ? params : undefined,
        }
      );

      // Check if API returned success: false
      if (!response.data?.status || !response.data?.data) {
        // Throw error that will be caught in layout
        throw new DomainNotRecognizedError(response.data?.message || "Franchise domain not recognized");
      }

      const elapsed = Date.now() - startTime;

      return {
        ...response.data.data,
        whatsapp: response.data.data.whatsapp ?? null,
      };
    } catch (error) {
      // Re-throw DomainNotRecognizedError so layout can handle it
      if (error instanceof DomainNotRecognizedError) {
        throw error;
      }

      console.error(`[HeaderFooterService] Error for domain ${domain}:`, error);
      return handleAPIError(error, domain, startTime, this.getDefaultData.bind(this));
    }
  }

  private getDefaultData(): ProcessedHeaderFooterHomeData {
    return {
      header: {
        logo: null,
        menu: [
          { name: "Home", url: "/", access: true, status: true, is_globle: true, order_no: 1, group_ids: [] },
          { name: "About us", url: "/about", access: true, status: true, is_globle: true, order_no: 2, group_ids: [] },
          { name: "Programs", url: "/programs", access: true, status: true, is_globle: true, order_no: 3, group_ids: [] },
          { name: "Workshops", url: "/workshops", access: true, status: true, is_globle: true, order_no: 4, group_ids: [] },
          { name: "Class registration", url: "/class-registration", access: true, status: true, is_globle: true, order_no: 5, group_ids: [] },
        ],
      },
      banner: {
        ctaLink: "/programs",
        ctaText: "Discover Programs",
        heading: "Young Engineers",
        mobileImage: null,
        desktopImage: "https://yefranchisees.b-cdn.net/media/super_admin/1770269758435_56z6omnn7lg_video_AP_RT_1920x1080.png",
        welcome_text: "Welcome to Young Engineers",
        territory_name: "Global",
      },
      footer: {
        logo: null,
        footer_menu: [
          { name: "HOME", url: "/home", access: true, status: true, is_globle: true, order_no: 1 },
          { name: "ABOUT US", url: "/about", access: true, status: true, is_globle: true, order_no: 2 },
          { name: "PROGRAMS", url: "/programs", access: true, status: true, is_globle: true, order_no: 3 },
          { name: "WORKSHOPS", url: "/workshops", access: true, status: true, is_globle: true, order_no: 4 },
          { name: "CLASS REGISTRATION", url: "/class-registration", access: true, status: true, is_globle: true, order_no: 5 },
        ]
      },
      tenant: {
        isPreview: false,
        franchiseeId: "",
        status: "published",
        zoho_franchise_id: "",
        latitude: "20.5937",
        longitude: "78.9629",
        isDev: false,
      },
      whatsapp: null,
    };
  }
}

export const headerFooterService = new HeaderFooterService();
