import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CouponRule } from '../../domain/entities/coupon-rule.entity';
import { ICouponRuleRepository } from '../../domain/repositories/coupon-rule.repository.interface';

@Injectable()
export class CouponRuleRepository implements ICouponRuleRepository {
  constructor(
    @InjectRepository(CouponRule)
    private readonly repo: Repository<CouponRule>,
  ) {}

  async findByCouponId(couponId: string): Promise<CouponRule[]> {
    return this.repo.find({ where: { couponId } });
  }

  async createMany(rules: Partial<CouponRule>[]): Promise<CouponRule[]> {
    const entities = rules.map((r) => this.repo.create(r));
    return this.repo.save(entities);
  }

  async create(data: Partial<CouponRule>): Promise<CouponRule> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async save(rule: CouponRule): Promise<CouponRule> {
    return this.repo.save(rule);
  }

  async deletesByCouponId(couponId: string): Promise<void> {
    await this.repo.delete({ couponId });
  }
}
