import { UpiRepository } from "../repositories/UpiRepository.js";

export class UpiService {
  constructor(private readonly upiRepository = new UpiRepository()) {}

  async createUpi(upiId: string, createdBy?: bigint) {
    const count = await this.upiRepository.count();
    if (count >= 2) {
      throw new Error("Maximum of 2 UPI records allowed.");
    }
    return this.upiRepository.create(upiId, createdBy);
  }

  async getUpis() {
    return this.upiRepository.findAll();
  }

  async getUpiById(id: number) {
    const upi = await this.upiRepository.findById(id);
    if (!upi) {
      throw new Error("UPI not found");
    }
    return upi;
  }

  async updateUpi(id: number, upiId: string) {
    const existing = await this.upiRepository.findById(id);
    if (!existing) {
      throw new Error("UPI not found");
    }
    return this.upiRepository.update(id, upiId);
  }

  async deleteUpi(id: number) {
    const existing = await this.upiRepository.findById(id);
    if (!existing) {
      throw new Error("UPI not found");
    }
    return this.upiRepository.delete(id);
  }
}
