import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThan, IsNull } from 'typeorm';
import { SmsVerification, SmsVerificationType } from '../../domain/entities/sms-verification.entity';
import { ISmsVerificationRepository } from '../../domain/repositories/sms-verification.repository.interface';

@Injectable()
export class SmsVerificationRepository implements ISmsVerificationRepository {
  constructor(
    @InjectRepository(SmsVerification)
    private readonly repo: Repository<SmsVerification>,
  ) {}

  async create(data: {
    phone: string;
    code: string;
    type: SmsVerificationType;
    expiresAt: Date;
  }): Promise<SmsVerification> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async findLatestValid(
    phone: string,
    type: SmsVerificationType,
  ): Promise<SmsVerification | null> {
    return this.repo.findOne({
      where: {
        phone,
        type,
        expiresAt: MoreThan(new Date()),
        verifiedAt: IsNull(),
      },
      order: { createdAt: 'DESC' },
    });
  }

  async save(verification: SmsVerification): Promise<SmsVerification> {
    return this.repo.save(verification);
  }

  async getDailySendCount(phone: string): Promise<number> {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    return this.repo.count({
      where: {
        phone,
        createdAt: MoreThan(today),
      },
    });
  }

  async deleteExpired(): Promise<number> {
    const result = await this.repo
      .createQueryBuilder()
      .delete()
      .where('expires_at < :now', { now: new Date() })
      .andWhere('verified_at IS NOT NULL OR expires_at < :cutoff', {
        cutoff: new Date(Date.now() - 24 * 60 * 60 * 1000), // 24h grace
      })
      .execute();

    return result.affected || 0;
  }
}
