import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { OldCreditAnalysis } from '../../database/tenant/entities/old-credit-analysis.entity';
import { NewCreditAnalysis } from '../../database/tenant/entities/new-credit-analysis.entity';
import { Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@Injectable()
export class CreditAnalysisService {
  constructor(
    private tenantConn: TenantConnectionService,
    @Inject(REQUEST) private request: Request,
  ) {}

  private sub() { return (this.request as any).tenantSubdomain as string; }
  private async ds() { return this.tenantConn.getTenantDataSource(this.sub()); }

  // ── Old Credit Analysis ────────────────────────────────────────────────────
  async listOld(q?: string, applicationId?: string, page = 1, limit = 20) {
    const ds = await this.ds();
    const r = ds.getRepository(OldCreditAnalysis);
    const qb = r.createQueryBuilder('oca').where('oca.deletedAt IS NULL').orderBy('oca.createdAt', 'DESC');
    if (q) qb.andWhere('oca.memberName LIKE :q', { q: `%${q}%` });
    if (applicationId) qb.andWhere('oca.applicationId = :applicationId', { applicationId });
    const total = await qb.getCount();
    const items = await qb.skip((page - 1) * limit).take(limit).getMany();
    return { items, total, page, limit };
  }

  async findOneOld(id: string) {
    const ds = await this.ds();
    const e = await ds.getRepository(OldCreditAnalysis).findOne({ where: { id } });
    if (!e) throw new NotFoundException('Old credit analysis not found');
    return e;
  }

  async createOld(dto: Partial<OldCreditAnalysis>) {
    const ds = await this.ds();
    const r = ds.getRepository(OldCreditAnalysis);
    return r.save(r.create({ ...dto, status: dto.status ?? 'draft' }));
  }

  async updateOld(id: string, dto: Partial<OldCreditAnalysis>) {
    const ds = await this.ds();
    const r = ds.getRepository(OldCreditAnalysis);
    const e = await this.findOneOld(id);
    return r.save(Object.assign(e, dto));
  }

  async removeOld(id: string) {
    const ds = await this.ds();
    await ds.getRepository(OldCreditAnalysis).softDelete(id);
    return { id };
  }

  // ── New Credit Analysis ────────────────────────────────────────────────────
  async listNew(q?: string, applicationId?: string, page = 1, limit = 20) {
    const ds = await this.ds();
    const r = ds.getRepository(NewCreditAnalysis);
    const qb = r.createQueryBuilder('nca').where('nca.deletedAt IS NULL').orderBy('nca.createdAt', 'DESC');
    if (q) qb.andWhere('nca.memberName LIKE :q', { q: `%${q}%` });
    if (applicationId) qb.andWhere('nca.applicationId = :applicationId', { applicationId });
    const total = await qb.getCount();
    const items = await qb.skip((page - 1) * limit).take(limit).getMany();
    return { items, total, page, limit };
  }

  async findOneNew(id: string) {
    const ds = await this.ds();
    const e = await ds.getRepository(NewCreditAnalysis).findOne({ where: { id } });
    if (!e) throw new NotFoundException('New credit analysis not found');
    return e;
  }

  async createNew(dto: Partial<NewCreditAnalysis>) {
    const ds = await this.ds();
    const r = ds.getRepository(NewCreditAnalysis);
    return r.save(r.create({ ...dto, status: dto.status ?? 'draft' }));
  }

  async updateNew(id: string, dto: Partial<NewCreditAnalysis>) {
    const ds = await this.ds();
    const r = ds.getRepository(NewCreditAnalysis);
    const e = await this.findOneNew(id);
    return r.save(Object.assign(e, dto));
  }

  async removeNew(id: string) {
    const ds = await this.ds();
    await ds.getRepository(NewCreditAnalysis).softDelete(id);
    return { id };
  }
}
