import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import {
  createErrorLog,
  createErrorLogSchema,
  hasErrorLogViewAccessToken,
  listErrorLogs,
  setupErrorLogTable,
} from '../services/error-log-service.js';

const errorLogListQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(200).optional(),
});

export async function registerErrorLogRoutes(app: FastifyInstance) {
  app.post('/api/error-logs/setup', async () => {
    return setupErrorLogTable();
  });

  app.get('/api/error-logs', async (request, reply) => {
    const accessToken = request.headers['x-access-token'];

    if (!hasErrorLogViewAccessToken(accessToken)) {
      reply.status(403);
      return {
        ok: false,
        message: '에러 로그 조회 권한이 없습니다.',
      };
    }

    const query = errorLogListQuerySchema.parse(request.query ?? {});
    const items = await listErrorLogs(query.limit ?? 50);

    return {
      ok: true,
      items,
    };
  });

  app.post('/api/error-logs/report', async (request) => {
    const payload = createErrorLogSchema.parse(request.body);
    const item = await createErrorLog(payload);

    return {
      ok: true,
      item,
    };
  });
}
