import { Injectable, BadRequestException, InternalServerErrorException } from '@nestjs/common';
import { BillingService } from '../billing/billing.service';
import { GrantPremiumDto } from './admin.dto';
import { Logger } from 'pino-nestjs';

@Injectable()
export class AdminService {
  constructor(
    private readonly logger: Logger,
    private readonly billingService: BillingService,
  ) {}

  async grantPremium(body: GrantPremiumDto) {
    const { user_id, days, reason } = body;

    if (!user_id || !days) {
      throw new BadRequestException('user_id and days required');
    }

    const daysCount = days; //TODO: verify
    if (isNaN(daysCount) || daysCount <= 0) {
      throw new BadRequestException('days must be a positive integer');
    }

    try {
      return await this.billingService.grantPremium({
        user_id,
        days: daysCount,
        source: 'manual',
        eventType: 'manual_grant',
        metadata: { reason },
      });
    } catch (error: any) {
      this.logger.error('Exception while granting premium access', error);
      throw new InternalServerErrorException(error?.message || 'Failed to grant premium access');
    }
  }
}
