import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Plan } from './entities/plan.entity';
import { JobPackage } from './entities/job-package.entity';

@Injectable()
export class PlansService {
  constructor(
    @InjectRepository(Plan)
    private plansRepository: Repository<Plan>,
    @InjectRepository(JobPackage)
    private packagesRepository: Repository<JobPackage>,
  ) {}

  async findAllPlans() {
    return await this.plansRepository.find({
      // return all plans, active first
      order: { is_active: 'DESC' },
    });
  }

  async findAllPackages() {
    return await this.packagesRepository.find({
      order: { is_active: 'DESC' },
    });
  }

  // --- Plans CRUD ---

  async createPlan(data: Partial<Plan>) {
    const plan = this.plansRepository.create(data);
    return await this.plansRepository.save(plan);
  }

  async updatePlan(code: string, data: Partial<Plan>) {
    await this.plansRepository.update({ code }, data);
    return await this.plansRepository.findOne({ where: { code } });
  }

  async deletePlan(code: string) {
    return await this.plansRepository.delete({ code });
  }

  // --- Packages CRUD ---

  async createPackage(data: Partial<JobPackage>) {
    const pkg = this.packagesRepository.create(data);
    return await this.packagesRepository.save(pkg);
  }

  async updatePackage(code: string, data: Partial<JobPackage>) {
    await this.packagesRepository.update({ code }, data);
    return await this.packagesRepository.findOne({ where: { code } });
  }

  async deletePackage(code: string) {
    return await this.packagesRepository.delete({ code });
  }
}
