import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SmsLog, SmsDeliveryStatus } from '../../domain/entities/sms-log.entity';
import { SmsVerificationType } from '../../domain/entities/sms-verification.entity';
import { ISmsLogRepository } from '../../domain/repositories/sms-log.repository.interface';

@Injectable()
export class SmsLogRepository implements ISmsLogRepository {
  constructor(
    @InjectRepository(SmsLog)
    private readonly repo: Repository<SmsLog>,
  ) {}

  async create(data: {
    phone: string;
    type: SmsVerificationType;
    status: SmsDeliveryStatus;
    provider?: string;
    providerId?: string;
    errorMsg?: string;
    userId?: string;
  }): Promise<SmsLog> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async findByPhone(
    phone: string,
    options?: { limit?: number; offset?: number },
  ): Promise<SmsLog[]> {
    return this.repo.find({
      where: { phone },
      order: { createdAt: 'DESC' },
      take: options?.limit || 20,
      skip: options?.offset || 0,
    });
  }

  async updateStatus(
    id: string,
    status: SmsDeliveryStatus,
    providerId?: string,
    errorMsg?: string,
  ): Promise<void> {
    await this.repo.update(id, {
      status,
      ...(providerId && { providerId }),
      ...(errorMsg && { errorMsg }),
    });
  }
}
