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

export async function handleCategories(request: Request, env: NavEnv): Promise<Response> {
  if (request.method === 'GET') {
    let categories = await getCategories(env.NAV_KV);
    if (!categories.length) {
      const sites = await getSites(env.NAV_KV);
      categories = [...new Set(sites.map((s) => s.category).filter(Boolean) as string[])];
      if (categories.length) await putCategories(env.NAV_KV, categories);
    }
    return new Response(JSON.stringify(categories), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  if (request.method === 'POST') {
    if (!(await verifyAuth(request, env))) {
      return new Response('Unauthorized', { status: 401, headers: corsHeaders });
    }
    const { name } = (await request.json()) as { name?: string };
    if (!name || !name.trim()) {
      return new Response('Bad Request', { status: 400, headers: corsHeaders });
    }
    const categories = await getCategories(env.NAV_KV);
    if (!categories.includes(name.trim())) {
      categories.push(name.trim());
      await putCategories(env.NAV_KV, categories);
    }
    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 handleCategory(request: Request, env: NavEnv, name: string): Promise<Response> {
  if (!name) return new Response('Bad Request', { status: 400, headers: corsHeaders });
  if (!(await verifyAuth(request, env))) {
    return new Response('Unauthorized', { status: 401, headers: corsHeaders });
  }
  const categories = await getCategories(env.NAV_KV);

  if (request.method === 'DELETE') {
    const filtered = categories.filter((c) => c !== name);
    await putCategories(env.NAV_KV, filtered);
    return new Response(JSON.stringify({ success: true }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  if (request.method === 'PUT') {
    const body = (await request.json()) as { name?: string };
    const newName = (body?.name || '').trim();
    if (!newName) return new Response('Bad Request', { status: 400, headers: corsHeaders });
    const updated = categories.map((c) => (c === name ? newName : c));
    const unique = Array.from(new Set(updated));
    await putCategories(env.NAV_KV, unique);
    const sites = await getSites(env.NAV_KV);
    const updatedSites = sites.map((site) =>
      site.category === name ? { ...site, category: newName } : site
    );
    await putSites(env.NAV_KV, updatedSites);
    return new Response(JSON.stringify({ success: true }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  return new Response('Method not allowed', { status: 405, headers: corsHeaders });
}
