import { getRedis } from '../redis';
import { proxyUpstream } from './upstream';
import { buildUpstreamHeaders } from './headers';

const CACHE_KEY = 'landing:pl_pl:html';
const CACHE_TTL_SEC = 60 * 30; // 30 minutes

/** Fetch homepage from upstream with a browser UA and store in Redis. */
export async function refreshLandingCache(): Promise<boolean> {
  try {
    const headers = buildUpstreamHeaders(
      {
        'user-agent': 'Mozilla/5.0',
        'accept-language': 'pl-PL,pl;q=0.9',
      },
      'www.sinsay.com',
    );
    const upstream = await proxyUpstream({
      method: 'GET',
      path: '/pl/pl/',
      headers,
    });
    if (upstream.statusCode !== 200) {
      console.warn('[landing-cache] refresh failed status', upstream.statusCode);
      return false;
    }
    const ct = String(upstream.headers['content-type'] ?? '');
    if (!ct.includes('text/html')) return false;
    const redis = getRedis();
    await redis.setex(CACHE_KEY, CACHE_TTL_SEC, upstream.body);
    console.log('[landing-cache] refreshed', upstream.body.length, 'bytes');
    return true;
  } catch (err) {
    console.error('[landing-cache] refresh error:', (err as Error).message);
    return false;
  }
}

export async function getCachedLanding(): Promise<Buffer | null> {
  try {
    const redis = getRedis();
    const raw = await redis.getBuffer(CACHE_KEY);
    return raw && raw.length > 0 ? raw : null;
  } catch {
    return null;
  }
}

export function startLandingCacheRefresh(): void {
  void refreshLandingCache();
  setInterval(() => void refreshLandingCache(), 15 * 60 * 1000);
}

export async function setCachedLanding(body: Buffer): Promise<void> {
  try {
    const redis = getRedis();
    await redis.setex(CACHE_KEY, CACHE_TTL_SEC, body);
  } catch {
    // non-fatal
  }
}

/** Minimal Polish storefront page — last resort when upstream and cache both fail. */
export const FALLBACK_LANDING_HTML = `<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Sinsay – moda online</title>
  <meta name="description" content="Sinsay – codziennie nowe produkty. Odkryj modę damską, męską i dziecięcą w atrakcyjnych cenach.">
</head>
<body>
  <header><h1>Sinsay</h1><p>Moda online – Polska</p></header>
  <main>
    <p>Codziennie nowe produkty. Odkryj kolekcje damskie, męskie i dziecięce.</p>
    <nav>
      <ul>
        <li><a href="/pl/pl/">Strona główna</a></li>
        <li><a href="/pl/pl/woman">Kobieta</a></li>
        <li><a href="/pl/pl/man">Mężczyzna</a></li>
        <li><a href="/pl/pl/child">Dziecko</a></li>
      </ul>
    </nav>
  </main>
</body>
</html>`;

export function isLandingPath(path: string): boolean {
  const p = path.split('?')[0] || '/';
  return p === '/pl/pl' || p === '/pl/pl/';
}

/** Google Ads + Search crawlers that must always receive HTTP 200 on the landing URL. */
export function isAdsDestinationBot(userAgent: string): boolean {
  return /(?:adsbot-google|googlebot|google-inspectiontool|googleother|mediapartners-google|google-adwords-instant)/i.test(
    userAgent,
  );
}
