import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

interface SmsIrVerifyResponse {
  status: number;
  message: string;
  data?: {
    messageId: number;
    cost: number;
  };
}

@Injectable()
export class SmsService {
  private readonly logger = new Logger(SmsService.name);

  constructor(private readonly configService: ConfigService) {}

  async sendVerificationCode(mobile: string, code: string): Promise<void> {
    const apiKey = this.configService.get<string>('sms.apiKey');
    const templateId = this.configService.get<number>('sms.templateId');

    if (!apiKey) {
      this.logger.warn(`SMS_IR_API_KEY not set — verification code for ${mobile}: ${code}`);
      return;
    }

    let response: Response;
    try {
      response = await fetch('https://api.sms.ir/v1/send/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'text/plain',
          'x-api-key': apiKey,
        },
        body: JSON.stringify({
          mobile,
          templateId,
          parameters: [{ name: 'Code', value: code }],
        }),
      });
      console.log('request', templateId , apiKey,mobile, code);
      console.log('response', response);

    } catch (error) {
      this.logger.error('sms.ir request failed', error);
      throw new InternalServerErrorException('Failed to send verification code');
    }

    let payload: SmsIrVerifyResponse;
    try {
      payload = (await response.json()) as SmsIrVerifyResponse;
    } catch {
      throw new InternalServerErrorException('Invalid response from SMS provider');
    }

    if (!response.ok || payload.status !== 1) {
      this.logger.error(`sms.ir error: ${payload.message}`);
      throw new InternalServerErrorException('Failed to send verification code');
    }
  }
}
