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

@Injectable()
export class SmsService {
    private readonly logger = new Logger(SmsService.name);
    private twilioClient: any | null = null;
    private twilioFrom: string | undefined;
    private isProd: boolean;

    constructor(private readonly config: ConfigService) {
        this.isProd = (process.env.NODE_ENV || '').toLowerCase() === 'production';

        const sid = this.config.get<string>('TWILIO_SID');
        const token = this.config.get<string>('TWILIO_TOKEN');
        this.twilioFrom = this.config.get<string>('TWILIO_FROM');

        if (sid && token) {
            try {
                // eslint-disable-next-line @typescript-eslint/no-var-requires
                const { Twilio } = require('twilio');
                this.twilioClient = new Twilio(sid, token);
            } catch {
                this.logger.error('Twilio SDK not available. Install "twilio" to enable SMS.');
            }
        } else if (this.isProd) {
            this.logger.warn('Missing TWILIO_SID/TOKEN in production.');
        }
    }

    async sendSms(to: string, body: string): Promise<{ ok: boolean; error?: string }> {
        if (!to || !/^\+\d{7,15}$/.test(to.trim())) {
            this.logger.warn(`Skipping SMS to invalid number: ${to}`);
            return { ok: false, error: 'Invalid phone number format' };
        }

        if (!this.twilioClient || !this.twilioFrom) {
            if (!this.isProd) {
                this.logger.log(`[DEV] SMS to=${to} body=${body.slice(0, 80)}...`);
                return { ok: true };
            }
            return { ok: false, error: 'SMS provider not configured' };
        }

        try {
            // Strip control characters to prevent log/gateway injection
            const sanitizedBody = body.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
            await this.twilioClient.messages.create({
                body: sanitizedBody,
                from: this.twilioFrom,
                to,
            });
            return { ok: true };
        } catch (err: any) {
            this.logger.error(`SMS send failed to=${to}: ${err?.message}`);
            return { ok: false, error: 'Failed to send SMS' };
        }
    }
}
