import { Injectable } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { ExternalGuarantor } from '../../database/tenant/entities/external-guarantor.entity';
import { ILike } from 'typeorm';

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

  private repo(tenant: string) {
    return this.tenantConn.getDataSource(tenant).getRepository(ExternalGuarantor);
  }

  async search(tenant: string, q: string, limit = 20) {
    const repo = this.repo(tenant);
    if (q?.trim()) {
      return repo.find({
        where: [
          { name: ILike(`%${q}%`) },
          { nameEn: ILike(`%${q}%`) },
          { citizenshipNo: ILike(`%${q}%`) },
          { contactNumber: ILike(`%${q}%`) },
        ],
        take: limit,
        withDeleted: false,
      });
    }
    return repo.find({ take: limit, order: { createdAt: 'DESC' } });
  }

  async findOne(tenant: string, id: string) {
    return this.repo(tenant).findOne({ where: { id } });
  }

  async create(tenant: string, body: Partial<ExternalGuarantor>, userId?: string) {
    const repo = this.repo(tenant);
    const record = repo.create({ ...body, createdBy: userId });
    return repo.save(record);
  }

  async update(tenant: string, id: string, body: Partial<ExternalGuarantor>) {
    const repo = this.repo(tenant);
    await repo.update(id, body);
    return repo.findOne({ where: { id } });
  }

  async remove(tenant: string, id: string) {
    await this.repo(tenant).softDelete(id);
    return { ok: true };
  }
}
