import { Response, NextFunction } from 'express';
import { AuthenticatedRequest, ApiResponse } from '../../shared/types/index.js';
import { featureFlagsService } from './services/feature-flags.instance.js';

export const featureFlagsController = {
  /**
   * Get all flags (Admin only ideally)
   */
  async getAllFlags(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const flags = await featureFlagsService.findAllFlagsIncludingInactive();
      const response: ApiResponse = {
        success: true,
        data: flags,
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Evaluate flags for current tenant
   */
  async evaluateFlags(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const { codes } = req.body;
      if (!Array.isArray(codes)) {
        throw new Error('Codes must be an array of strings');
      }

      const results = await featureFlagsService.evaluateFlags(codes, req.user!.tenantId);
      const response: ApiResponse = {
        success: true,
        data: results,
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Create or Update an override for a tenant
   */
  async upsertOverride(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const { flagId, tenantId, enabled, expiresAt } = req.body;
      
      const existing = await featureFlagsService.findOverride(flagId, tenantId);
      let result;
      
      if (existing) {
        result = await featureFlagsService.updateOverride(existing.id, { enabled, expiresAt });
      } else {
        result = await featureFlagsService.createOverride({ flagId, tenantId, enabled, expiresAt }, req.user!.userId);
      }

      const response: ApiResponse = {
        success: true,
        data: result,
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  }
};
