import {
  Injectable,
  InternalServerErrorException,
  BadRequestException,
} from '@nestjs/common';
import { DataSource } from 'typeorm';
import { WalletService } from '../wallet/wallet.service';
import { FeatureCost } from './entities/feature-cost.entity';
import { UsageRecord } from './entities/usage-record.entity';

@Injectable()
export class FeatureUsageService {
  constructor(
    private dataSource: DataSource,
    private walletService: WalletService,
  ) {}

  async unlockFeature(userId: number, featureKey: string, refId: number) {
    return await this.dataSource.transaction(async (manager) => {
      // 1. Idempotency Check (Don't charge twice)
      // Check if already unlocked
      const existing = await manager.query(
        'SELECT id FROM usage_records WHERE user_id = ? AND feature_key = ? AND reference_id = ?',
        [userId, featureKey, refId],
      );
      if (existing.length > 0) {
        return { success: true, message: 'Already unlocked', charged: false };
      }

      // 2. Get Cost
      const [costRule] = await manager.query(
        'SELECT * FROM feature_costs WHERE feature_key = ? AND is_active = 1',
        [featureKey],
      );

      // If no rule exists, maybe it's free or invalid. Let's assume invalid for safety.
      if (!costRule) {
        throw new InternalServerErrorException(
          `Feature ${featureKey} cost not configured`,
        );
      }

      // 3. Debit Wallet (Pass the transaction manager down!)
      // Ensure we catch the specific "Insufficient credits" error from wallet service
      await this.walletService.debitWallet(
        userId,
        costRule.credit_type,
        costRule.cost_credits,
        `Unlock Feature: ${featureKey}`,
        'usage_record', // refType
        refId, // Temporary RefID (will be inserted next)
        manager,
      );

      // 4. Record Usage
      await manager.query(
        'INSERT INTO usage_records (user_id, feature_key, units_used, reference_id) VALUES (?, ?, ?, ?)',
        [userId, featureKey, 1, refId],
      );

      return {
        success: true,
        charged: true,
        credits_deducted: costRule.cost_credits,
        message: 'Feature unlocked successfully',
      };
    });
  }
}
