import type { FastifyInstance } from 'fastify';
import type { SecretService } from '../services/secret.service.js';

export function registerSecretRoutes(
  app: FastifyInstance,
  service: SecretService,
): void {
  app.get('/api/v1/secrets', async () => {
    return service.list();
  });

  app.get<{ Params: { id: string }; Querystring: { reveal?: string } }>(
    '/api/v1/secrets/:id',
    async (request) => {
      const secret = await service.getById(request.params.id);
      // ?reveal=true → resolve `data` through the backing driver. Without
      // reveal we return the raw row, which for non-plaintext backends has
      // an empty `data` (the real values live in the backend; only the
      // externalRef is on the row). The CLI's `describe secret` already
      // masks values by default; --show-values flips this query param so the
      // describe output matches what the user expects pre/post migration.
      if (request.query.reveal === 'true') {
        const resolved = await service.resolveData(secret).catch(() => null);
        if (resolved !== null) {
          return { ...secret, data: resolved };
        }
      }
      return secret;
    },
  );

  app.post('/api/v1/secrets', async (request, reply) => {
    const secret = await service.create(request.body);
    reply.code(201);
    return secret;
  });

  app.put<{ Params: { id: string } }>('/api/v1/secrets/:id', async (request) => {
    return service.update(request.params.id, request.body);
  });

  app.delete<{ Params: { id: string } }>('/api/v1/secrets/:id', async (request, reply) => {
    await service.delete(request.params.id);
    reply.code(204);
  });
}
