import type { FastifyInstance } from 'fastify';
import { getProviderStatus, unloadProvider, unloadModel } from '../services/provider-status.js';

export function registerProviderRoutes(app: FastifyInstance): void {
  app.get('/api/providers/status', async (_req, reply) => {
    try {
      const result = await getProviderStatus();
      return reply.send(result);
    } catch (err) {
      return reply.status(502).send({
        error: 'failed to query provider statuses',
        detail: err instanceof Error ? err.message : String(err),
      });
    }
  });

  app.post('/api/providers/:providerId/unload', async (req, reply) => {
    const params = req.params as { providerId: string };
    const ok = await unloadProvider(params.providerId);
    if (!ok) {
      return reply.status(404).send({ error: `provider ${params.providerId} not found or unload failed` });
    }
    return reply.send({ status: 'ok', providerId: params.providerId });
  });

  app.post('/api/providers/:providerId/unload/:modelId', async (req, reply) => {
    const params = req.params as { providerId: string; modelId: string };
    const ok = await unloadModel(params.providerId, params.modelId);
    if (!ok) {
      return reply.status(404).send({
        error: `unload failed for provider ${params.providerId}, model ${params.modelId}`,
      });
    }
    return reply.send({ status: 'ok', providerId: params.providerId, modelId: params.modelId });
  });
}
