/**
 * Headless WordPress REST API client.
 * Fetches products, categories, posts from the existing WP/WC backend.
 *
 * All fetches use Next.js native `fetch` with revalidation tags so we can
 * trigger ISR refreshes from the WP side later if needed.
 */

import { site } from './site';

const WP = site.wpBase;

// ---- Types ----------------------------------------------------------------

export interface WPMedia {
    source_url: string;
    media_details?: {
        sizes?: Record<string, { source_url: string; width: number; height: number }>;
    };
    alt_text?: string;
}

export interface WPProductCat {
    id: number;
    slug: string;
    name: string;
    count: number;
    parent: number;
    description: string;
}

export interface WPProduct {
    id: number;
    slug: string;
    title: { rendered: string };
    excerpt?: { rendered: string };
    content?: { rendered: string };
    link: string;
    featured_media: number;
    product_cat?: number[];
    _embedded?: {
        'wp:featuredmedia'?: WPMedia[];
        'wp:term'?: WPProductCat[][];
    };
}

export interface WPPost {
    id: number;
    slug: string;
    title: { rendered: string };
    excerpt: { rendered: string };
    date: string;
    link: string;
    featured_media: number;
    categories: number[];
    _embedded?: {
        'wp:featuredmedia'?: WPMedia[];
        'wp:term'?: { id: number; name: string; slug: string }[][];
    };
}

// ---- Helpers --------------------------------------------------------------

async function wpFetch<T>(path: string, opts: { tag?: string; revalidate?: number } = {}): Promise<T> {
    const url = path.startsWith('http') ? path : `${WP}${path}`;
    const res = await fetch(url, {
        next: {
            revalidate: opts.revalidate ?? 600, // 10 min default
            tags: opts.tag ? [opts.tag] : undefined,
        },
    });
    if (!res.ok) {
        throw new Error(`WP fetch failed (${res.status}) ${url}`);
    }
    return res.json() as Promise<T>;
}

// ---- Products -------------------------------------------------------------

export async function getProducts(params: {
    perPage?: number;
    categorySlug?: string;
    search?: string;
} = {}): Promise<WPProduct[]> {
    const qs = new URLSearchParams();
    qs.set('per_page', String(params.perPage ?? 12));
    qs.set('_embed', 'true');
    if (params.search) qs.set('search', params.search);

    let path = `/wp-json/wp/v2/product?${qs.toString()}`;
    if (params.categorySlug) {
        const cat = await getCategoryBySlug(params.categorySlug);
        if (cat) path += `&product_cat=${cat.id}`;
    }
    return wpFetch<WPProduct[]>(path, { tag: 'products' });
}

export async function getProductBySlug(slug: string): Promise<WPProduct | null> {
    const items = await wpFetch<WPProduct[]>(
        `/wp-json/wp/v2/product?slug=${encodeURIComponent(slug)}&_embed=true`,
        { tag: `product:${slug}` }
    );
    return items[0] ?? null;
}

// ---- Categories -----------------------------------------------------------

export async function getCategories(): Promise<WPProductCat[]> {
    return wpFetch<WPProductCat[]>(
        `/wp-json/wp/v2/product_cat?per_page=100&hide_empty=false&orderby=name`,
        { tag: 'categories' }
    );
}

export async function getCategoryBySlug(slug: string): Promise<WPProductCat | null> {
    const items = await wpFetch<WPProductCat[]>(
        `/wp-json/wp/v2/product_cat?slug=${encodeURIComponent(slug)}`,
        { tag: `category:${slug}` }
    );
    return items[0] ?? null;
}

// ---- Posts ----------------------------------------------------------------

export async function getPosts(perPage = 6): Promise<WPPost[]> {
    return wpFetch<WPPost[]>(
        `/wp-json/wp/v2/posts?per_page=${perPage}&_embed=true&orderby=date&order=desc`,
        { tag: 'posts' }
    );
}

// ---- Image helpers --------------------------------------------------------

export function productImage(p: WPProduct, size: 'thumbnail' | 'medium' | 'medium_large' | 'large' = 'medium_large'): string {
    const media = p._embedded?.['wp:featuredmedia']?.[0];
    if (!media) return '';
    const sized = media.media_details?.sizes?.[size]?.source_url;
    return sized ?? media.source_url ?? '';
}

export function productCategory(p: WPProduct): string {
    const term = p._embedded?.['wp:term']?.[0]?.[0];
    return term?.name ?? '';
}

export function postImage(p: WPPost): string {
    return p._embedded?.['wp:featuredmedia']?.[0]?.source_url ?? '';
}

export function postCategory(p: WPPost): string {
    return p._embedded?.['wp:term']?.[0]?.[0]?.name ?? 'Blog';
}

/** Strip HTML tags from WP rendered content for safe display in cards. */
export function plainText(html: string, maxLen = 160): string {
    const stripped = html.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
    return stripped.length > maxLen ? stripped.slice(0, maxLen) + '…' : stripped;
}
