import { handleListGet } from './api/list.js';
import { handleRandomGet } from './api/random.js';

export default {
  /**
   * @param {Request} request
   * @param {{ ASSETS: { fetch(input: Request | string, init?: RequestInit): Promise<Response> } }} env
   */
  async fetch(request, env) {
    const url = new URL(request.url);
    const pathname = normalizePath(url.pathname);

    if (pathname === '/api/random') return routeApiGet(request, env, handleRandomGet);
    if (pathname === '/api/list') return routeApiGet(request, env, handleListGet);

    return env.ASSETS.fetch(request);
  },
};

/**
 * @param {string} pathname
 */
function normalizePath(pathname) {
  if (pathname.length > 1 && pathname.endsWith('/')) return pathname.replace(/\/+$/, '');
  return pathname;
}

/**
 * @param {Request} request
 * @param {{ ASSETS?: { fetch(input: RequestInfo, init?: RequestInit): Promise<Response> } }} env
 * @param {(request: Request, env: object) => Promise<Response> | Response} handler
 */
async function routeApiGet(request, env, handler) {
  if (request.method !== 'GET') {
    return new Response('Method Not Allowed', { status: 405 });
  }
  return handler(request, env);
}
