import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { Subscription, SubscriptionStatus } from '../../domain/entities/subscription.entity';

@Injectable()
export class SubscriptionRepository {
  private readonly repo: Repository<Subscription>;

  constructor(private readonly dataSource: DataSource) {
    this.repo = this.dataSource.getRepository(Subscription);
  }

  async findByTenantId(tenantId: string): Promise<Subscription | null> {
    return this.repo.findOne({
      where: { tenantId },
      order: { createdAt: 'DESC' },
    });
  }

  async findById(id: string): Promise<Subscription | null> {
    return this.repo.findOne({ where: { id } });
  }

  async findExpired(): Promise<Subscription[]> {
    return this.repo
      .createQueryBuilder('s')
      .where('s.currentPeriodEnd < NOW()')
      .andWhere('s.status IN (:...statuses)', {
        statuses: [SubscriptionStatus.ACTIVE, SubscriptionStatus.TRIALING],
      })
      .getMany();
  }

  async findCancelAtPeriodEnd(): Promise<Subscription[]> {
    return this.repo.find({ where: { cancelAtPeriodEnd: true, status: SubscriptionStatus.ACTIVE } });
  }

  async save(subscription: Subscription): Promise<Subscription> {
    return this.repo.save(subscription);
  }
}
