import type { FastifyInstance } from 'fastify';
import { BadRequestError, requireAdmin } from '../../lib/auth.js';
import { deleteEnvVar, getEnvVar, getEnvVars, upsertEnvVar } from './repository.js';
import { EnvVarInputSchema, EnvVarParamsSchema } from './types.js';

export async function envRoutes(fastify: FastifyInstance) {
  fastify.get('/env', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    return reply.send(await getEnvVars());
  });

  fastify.get('/env/:id', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    const params = EnvVarParamsSchema.parse(req.params);
    const envVar = await getEnvVar(params.id);
    if (!envVar) return reply.code(404).send({ error: 'Environment variable not found' });
    return reply.send(envVar);
  });

  fastify.post('/env', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const input = EnvVarInputSchema.parse(req.body) as { name: string };
      return reply.code(201).send(await upsertEnvVar(input));
    } catch (error) {
      if (error instanceof Error) throw new BadRequestError(error.message);
      throw error;
    }
  });

  fastify.put('/env/:id', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const params = EnvVarParamsSchema.parse(req.params);
      const input = EnvVarInputSchema.parse({ ...(req.body as object), id: params.id }) as { name: string; id: string };
      return reply.send(await upsertEnvVar(input));
    } catch (error) {
      if (error instanceof Error) throw new BadRequestError(error.message);
      throw error;
    }
  });

  fastify.delete('/env/:id', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    const params = EnvVarParamsSchema.parse(req.params);
    const deleted = await deleteEnvVar(params.id);
    if (!deleted) return reply.code(404).send({ error: 'Environment variable not found' });
    return reply.code(204).send();
  });

  fastify.post('/env/sync-azure', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    return reply.send({ synced: 0, errors: ['Azure Key Vault sync is not configured in this local dashboard build.'] });
  });
}
