import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { Plan } from '../../domain/entities/plan.entity';

@Injectable()
export class PlanRepository {
  private readonly repo: Repository<Plan>;

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

  async findAll(): Promise<Plan[]> {
    return this.repo.find({ where: { isActive: true }, order: { monthlyPriceCentsUsd: 'ASC' } });
  }

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

  async findByName(name: string): Promise<Plan | null> {
    return this.repo.findOne({ where: { name } });
  }

  async save(plan: Plan): Promise<Plan> {
    return this.repo.save(plan);
  }

  async upsertSeedPlans(plans: Partial<Plan>[]): Promise<void> {
    for (const p of plans) {
      const existing = await this.repo.findOne({ where: { name: p.name } });
      if (!existing) {
        await this.repo.save(this.repo.create(p));
      } else {
        await this.repo.save(Object.assign(existing, p));
      }
    }
  }
}
