import { logger } from '@/lib/logger';
import type { AppEnv } from '@/types/hono';
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { requestId } from 'hono/request-id';
import { errorHandler } from './lib/http/error-handler';
import { requestIdMiddleware } from './lib/http/request-id';

export function createApp() {
  const app = new Hono<AppEnv>();

  app.use('*', requestIdMiddleware);
  app.use('*', errorHandler);

  const allowedOrigins = (Bun.env.CORS_ORIGIN ?? 'http://localhost:5173,http://127.0.0.1:5173')
    .split(',')
    .map((value) => value.trim())
    .filter(Boolean);

  app.use(
    '*',
    cors({
      origin: (origin) => {
        if (!origin) return allowedOrigins[0] ?? '';
        return allowedOrigins.includes(origin) ? origin : '';
      },
      allowHeaders: ['Authorization', 'Content-Type'],
      allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
      exposeHeaders: ['Content-Length'],
      maxAge: 600,
      credentials: true,
    })
  );

  app.use('*', async (c, next) => {
    const start = performance.now();
    await next();
    const durationMs = Number((performance.now() - start).toFixed(1));

    logger.info(
      {
        method: c.req.method,
        path: c.req.path,
        status: c.res.status,
        durationMs,
        requestId,
      },
      'http_request'
    );
  });

  return app;
}
