import type { NavEnv } from '../../env';
import { verifyAuth } from '../auth';
import { corsHeaders } from '../cors';
import { getCategories, getSites, putCategories, putSites, type SiteRecord } from '../../storage/kv-nav';

export async function handleSites(request: Request, env: NavEnv): Promise<Response> {
  if (request.method === 'GET') {
    const sitesData = await getSites(env.NAV_KV);
    const normalized = sitesData.map((s) => ({ ...s, clicks: typeof s.clicks === 'number' ? s.clicks : 0 }));
    return new Response(JSON.stringify(normalized), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  if (request.method === 'POST') {
    if (!(await verifyAuth(request, env))) {
      return new Response('Unauthorized', { status: 401, headers: corsHeaders });
    }
    const newSite = (await request.json()) as SiteRecord;
    const sites = await getSites(env.NAV_KV);
    const categories = await getCategories(env.NAV_KV);
    newSite.id = Date.now().toString();
    newSite.clicks = 0;
    sites.push(newSite);
    if (newSite.category && !categories.includes(newSite.category)) {
      categories.push(newSite.category);
      await putCategories(env.NAV_KV, categories);
    }
    await putSites(env.NAV_KV, sites);
    return new Response(JSON.stringify(newSite), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  return new Response('Method not allowed', { status: 405, headers: corsHeaders });
}

export async function handleSite(request: Request, env: NavEnv, id: string): Promise<Response> {
  const sites = await getSites(env.NAV_KV);
  const categories = await getCategories(env.NAV_KV);

  if (request.method === 'GET') {
    const site = sites.find((s) => s.id === id);
    if (!site) return new Response('Not Found', { status: 404, headers: corsHeaders });
    const normalized = { ...site, clicks: typeof site.clicks === 'number' ? site.clicks : 0 };
    return new Response(JSON.stringify(normalized), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  if (request.method === 'PUT') {
    if (!(await verifyAuth(request, env))) {
      return new Response('Unauthorized', { status: 401, headers: corsHeaders });
    }
    const updatedSite = (await request.json()) as Partial<SiteRecord>;
    const index = sites.findIndex((s) => s.id === id);
    if (index === -1) return new Response('Not Found', { status: 404, headers: corsHeaders });
    const existingClicks = typeof sites[index].clicks === 'number' ? sites[index].clicks : 0;
    sites[index] = { ...sites[index], ...updatedSite, id, clicks: existingClicks };
    if (updatedSite.category && !categories.includes(updatedSite.category)) {
      categories.push(updatedSite.category);
      await putCategories(env.NAV_KV, categories);
    }
    await putSites(env.NAV_KV, sites);
    return new Response(JSON.stringify(sites[index]), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  if (request.method === 'DELETE') {
    if (!(await verifyAuth(request, env))) {
      return new Response('Unauthorized', { status: 401, headers: corsHeaders });
    }
    const index = sites.findIndex((s) => s.id === id);
    if (index === -1) return new Response('Not Found', { status: 404, headers: corsHeaders });
    sites.splice(index, 1);
    await putSites(env.NAV_KV, sites);
    return new Response(JSON.stringify({ success: true }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  return new Response('Method not allowed', { status: 405, headers: corsHeaders });
}

export async function handleSiteClick(request: Request, env: NavEnv, id: string): Promise<Response> {
  if (request.method !== 'POST') {
    return new Response('Method not allowed', { status: 405, headers: corsHeaders });
  }
  const sites = await getSites(env.NAV_KV);
  const index = sites.findIndex((s) => s.id === id);
  if (index === -1) {
    return new Response('Not Found', { status: 404, headers: corsHeaders });
  }
  const site = sites[index];
  const prev = typeof site.clicks === 'number' ? site.clicks : 0;
  sites[index] = { ...site, clicks: prev + 1 };
  await putSites(env.NAV_KV, sites);
  return new Response(JSON.stringify({ success: true, clicks: prev + 1 }), {
    headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  });
}
