/**
 * Server-side API client for SSR
 * API key is stored securely on the server - never exposed to browser
 */

import type { CompanyInformation } from '../types/api/company-information';
import type { Service } from '../types/api/service';
import type { WebsitePhotos } from '../types/api/website-photos';

const API_URL = process.env.API_URL || 'http://localhost:3000/api/v1';
const API_KEY = process.env.API_KEY || '';

interface FetchOptions {
  cache?: RequestCache;
  revalidate?: number;
}

async function serverFetch<T>(endpoint: string, options: FetchOptions = {}): Promise<T | null> {
  const url = `${API_URL}${endpoint}`;
  
  try {
    const fetchOptions: RequestInit & { next?: { revalidate?: number } } = {
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
      },
      cache: options.cache,
    };
    
    if (options.revalidate) {
      fetchOptions.next = { revalidate: options.revalidate };
    }
    
    const response = await fetch(url, fetchOptions);

    if (!response.ok) {
      console.error(`[Server API] Error ${response.status} for ${endpoint}`);
      return null;
    }

    const json = await response.json();
    
    // Rails API returns { data: [...], meta: {...} }
    return json.data ?? json;
  } catch (error) {
    console.error(`[Server API] Failed to fetch ${endpoint}:`, error);
    return null;
  }
}

/**
 * Generic serverApi object for flexible endpoint access
 */
export const serverApi = {
  get: <T = unknown>(endpoint: string, options?: FetchOptions): Promise<T | null> => {
    return serverFetch<T>(endpoint, options || { revalidate: 60 });
  }
};

// Revalidate data every 60 seconds (ISR)
const defaultOptions: FetchOptions = { revalidate: 60 };

export async function getCompanyInformation(): Promise<CompanyInformation | null> {
  return serverFetch<CompanyInformation>('/public/company_information', defaultOptions);
}

/** Ads config (e.g. Meta Pixel). Returns { meta_pixel_id?: string } or {}. Only present when account has connected Meta Ads. */
export async function getAdsConfig(): Promise<{ meta_pixel_id?: string } | null> {
  const data = await serverFetch<{ meta_pixel_id?: string }>('/public/ads_config', defaultOptions);
  return data ?? null;
}

/** Extract Meta Pixel ID from ads config for use with <MetaPixel pixelId={...} />. Only returns a value when present and valid (numeric). */
export function getMetaPixelId(adsConfig: { meta_pixel_id?: string } | null | undefined): string | null {
  const id = adsConfig && typeof adsConfig === 'object' && 'meta_pixel_id' in adsConfig && adsConfig.meta_pixel_id;
  const str = id != null && id !== '' ? String(id).trim() : '';
  return str !== '' && str !== 'null' && /^\d+$/.test(str) ? str : null;
}

export async function getServices() {
  return serverFetch('/public/services', defaultOptions);
}

export async function getService(slug: string): Promise<Service | null> {
  return serverFetch<Service>(`/public/services/by_slug/${slug}`, defaultOptions);
}

export async function getLocations() {
  return serverFetch('/public/locations', defaultOptions);
}

export async function getLocation(slug: string) {
  return serverFetch(`/public/locations/by_slug/${slug}`, defaultOptions);
}

export async function getReviews() {
  return serverFetch('/public/reviews', defaultOptions);
}

export async function getFAQs() {
  return serverFetch('/public/faq_questions', defaultOptions);
}

export async function getBlogPosts() {
  return serverFetch('/public/blog_posts', defaultOptions);
}

export async function getBlogPost(slug: string) {
  return serverFetch(`/public/blog_posts/by_slug/${slug}`, defaultOptions);
}

export async function getTeamMembers() {
  return serverFetch('/public/team_members', defaultOptions);
}

export async function getWebsitePhotos(): Promise<WebsitePhotos | null> {
  return serverFetch<WebsitePhotos>('/public/website_photos', defaultOptions);
}

export async function getJobPostings() {
  return serverFetch('/public/job_postings', defaultOptions);
}

export async function getJobPosting(slug: string) {
  return serverFetch(`/public/job_postings/by_slug/${slug}`, defaultOptions);
}

export async function getSocialPosts() {
  return serverFetch('/public/social_posts', defaultOptions);
}

// Alias for testimonials (API uses "reviews")
export async function getTestimonials() {
  return getReviews();
}

/** Form definition for dynamic form rendering (fields may include optional placeholder). */
export async function getForm(formType: string) {
  type FormDefinition = import('../types/api/form').FormDefinition;
  return serverFetch<FormDefinition>(`/public/forms/${encodeURIComponent(formType)}`, defaultOptions);
}

