import type { NavEnv } from '../env';
import { corsHeaders } from './cors';
import { handleAuthCheck, handleAuthLogin } from './handlers/auth-handlers';
import { handleCategories, handleCategory } from './handlers/categories';
import { handleSite, handleSites, handleSiteClick } from './handlers/sites';

/** Worker `/api/*` 路由入口 */
export async function handleApiRequest(request: Request, env: NavEnv): Promise<Response> {
  if (request.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  const url = new URL(request.url);
  const path = url.pathname;

  try {
    if (path === '/api/sites') {
      return handleSites(request, env);
    }
    if (path === '/api/auth/login') {
      return handleAuthLogin(request, env);
    }
    if (path === '/api/auth/check') {
      return handleAuthCheck(request, env);
    }
    if (path.match(/^\/api\/sites\/[^/]+\/click$/)) {
      const id = path.split('/')[3]!;
      return handleSiteClick(request, env, id);
    }
    if (path.startsWith('/api/sites/')) {
      const id = path.split('/')[3]!;
      return handleSite(request, env, id);
    }
    if (path === '/api/categories') {
      return handleCategories(request, env);
    }
    if (path.startsWith('/api/categories/')) {
      const name = decodeURIComponent(path.split('/')[3] || '');
      return handleCategory(request, env, name);
    }

    return new Response('Not Found', { status: 404 });
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : String(error);
    return new Response('Internal Server Error: ' + message, {
      status: 500,
      headers: corsHeaders,
    });
  }
}
