// src/server/features/system/system.routes.ts
// HTTP handlers for system management routes

import { ZodTypeProvider } from 'fastify-type-provider-zod';
import { FastifyInstance } from 'fastify';
import { z } from 'zod';
import {
  updateLogConfigBodySchema,
  errorResponseSchema,
} from './system.schema';
import { loggerService } from '../../shared/lib/logger';
import { requireRole } from '../../shared/lib/auth';
import { USER_ROLES } from '@shared/constants/roles';

export const systemRoutes = async (fastify: FastifyInstance) => {
  const server = fastify.withTypeProvider<ZodTypeProvider>();

  // GET /logs
  server.get('/logs', {
    onRequest: [requireRole(USER_ROLES.GOD)],
    schema: {
      // REMOVED "response" schema to prevent Fastify from stripping our data
      // We trust the service to return the correct shape
      response: {
        200: z.any(), // Allow any response type for success case
        401: errorResponseSchema,
        403: errorResponseSchema,
      },
    },
  }, async (request, reply) => {
    // Send RAW config object (matches Frontend expectation)
    const config = loggerService.getConfig();
    return reply.code(200).send(config);
  });

  // PATCH /logs
  server.patch('/logs', {
    onRequest: [requireRole(USER_ROLES.GOD)],
    schema: {
      body: updateLogConfigBodySchema,
      // REMOVED "response" schema
      response: {
        200: z.any(), // Allow any response type for success case
        400: errorResponseSchema,
        401: errorResponseSchema,
        403: errorResponseSchema,
      },
    },
  }, async (request, reply) => {
    const { channel, level } = request.body;

    // 1. Update
    loggerService.updateConfig(channel, level);

    // 2. Fetch fresh config
    const newConfig = loggerService.getConfig();

    // Send RAW config object
    return reply.code(200).send(newConfig);
  });
};
