import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { LoanTitle } from '../../database/tenant/entities/loan-title.entity';
import { LoanPurpose } from '../../database/tenant/entities/loan-purpose.entity';

@Injectable()
export class LoanSettingsService {
  constructor(private tenantConn: TenantConnectionService) {}

  private async titleRepo(sub: string) {
    const ds = await this.tenantConn.getTenantDataSource(sub);
    return ds.getRepository(LoanTitle);
  }

  private async purposeRepo(sub: string) {
    const ds = await this.tenantConn.getTenantDataSource(sub);
    return ds.getRepository(LoanPurpose);
  }

  async listTitles(sub: string, officeId?: string) {
    const r = await this.titleRepo(sub);
    const where: any = {};
    if (officeId) where.officeId = officeId;
    return r.find({ where, order: { name: 'ASC' } });
  }

  async createTitle(sub: string, dto: any) {
    const r = await this.titleRepo(sub);
    return r.save(r.create(dto));
  }

  async updateTitle(sub: string, id: string, dto: any) {
    const r = await this.titleRepo(sub);
    const item = await r.findOne({ where: { id } });
    if (!item) throw new NotFoundException('Loan title not found');
    await r.update(id, dto);
    return r.findOne({ where: { id } });
  }

  async deleteTitle(sub: string, id: string) {
    const r = await this.titleRepo(sub);
    await r.softDelete(id);
    return { id };
  }

  async listPurposes(sub: string, officeId?: string) {
    const r = await this.purposeRepo(sub);
    const where: any = {};
    if (officeId) where.officeId = officeId;
    return r.find({ where, order: { name: 'ASC' } });
  }

  async createPurpose(sub: string, dto: any) {
    const r = await this.purposeRepo(sub);
    return r.save(r.create(dto));
  }

  async updatePurpose(sub: string, id: string, dto: any) {
    const r = await this.purposeRepo(sub);
    const item = await r.findOne({ where: { id } });
    if (!item) throw new NotFoundException('Loan purpose not found');
    await r.update(id, dto);
    return r.findOne({ where: { id } });
  }

  async deletePurpose(sub: string, id: string) {
    const r = await this.purposeRepo(sub);
    await r.softDelete(id);
    return { id };
  }
}
