import type { FastifyInstance } from 'fastify';
import type { ContainerManager } from '../k8s/container-manager.js';
import type { UserService } from '../db/user-service.js';
import type { LicenseTier } from '../types/user.js';

const VALID_TIERS: LicenseTier[] = ['free', 'pro', 'enterprise'];

export class AdminRoutes {
  private containerManager: ContainerManager;
  private userService: UserService;

  constructor(containerManager: ContainerManager, userService: UserService) {
    this.containerManager = containerManager;
    this.userService = userService;
  }

  register(app: FastifyInstance): void {
    app.post<{ Params: { userId: string }; Body: { tier: string } }>(
      '/admin/users/:userId/set-tier',
      async (req, reply) => {
        const { userId } = req.params;
        const { tier } = req.body;
        if (!VALID_TIERS.includes(tier as LicenseTier)) {
          return reply.code(400).send({ error: `Invalid tier. Must be one of: ${VALID_TIERS.join(', ')}` });
        }
        const license = await this.containerManager.applyLicenseTier(userId, tier as LicenseTier);
        return { userId, tier, license };
      }
    );

    app.post('/admin/migrate-licenses', async () => {
      return await this.userService.migrateAllLicenses();
    });
  }
}
