import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantConnectionService } from '../../database/tenant-connection.service';
import { MemberIncome } from '../../database/tenant/entities/member-income.entity';
import { MemberBusinessIncome } from '../../database/tenant/entities/member-business-income.entity';
import { MemberFinancial } from '../../database/tenant/entities/member-financial.entity';

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

  private async ds(sub: string) { return this.tenantConn.getTenantDataSource(sub); }

  async getIncomes(sub: string, memberId: string) {
    const ds = await this.ds(sub);
    return ds.getRepository(MemberIncome).find({ where: { memberId }, order: { createdAt: 'ASC' } });
  }

  async addIncome(sub: string, memberId: string, dto: any) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberIncome);
    return r.save(r.create({ ...dto, memberId }));
  }

  async updateIncome(sub: string, id: string, dto: any) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberIncome);
    const item = await r.findOne({ where: { id } });
    if (!item) throw new NotFoundException('Income not found');
    await r.update(id, dto);
    return r.findOne({ where: { id } });
  }

  async deleteIncome(sub: string, id: string) {
    const ds = await this.ds(sub);
    await ds.getRepository(MemberIncome).softDelete(id);
    return { id };
  }

  async bulkSaveIncomes(sub: string, memberId: string, items: any[]) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberIncome);
    await r.delete({ memberId });
    const saved = [];
    for (const i of items) { saved.push(await r.save(r.create({ ...i, memberId }))); }
    return saved;
  }

  async getBusinessIncomes(sub: string, memberId: string) {
    const ds = await this.ds(sub);
    return ds.getRepository(MemberBusinessIncome).find({ where: { memberId }, order: { createdAt: 'ASC' } });
  }

  async addBusinessIncome(sub: string, memberId: string, dto: any) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberBusinessIncome);
    return r.save(r.create({ ...dto, memberId }));
  }

  async updateBusinessIncome(sub: string, id: string, dto: any) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberBusinessIncome);
    const item = await r.findOne({ where: { id } });
    if (!item) throw new NotFoundException('Business income not found');
    await r.update(id, dto);
    return r.findOne({ where: { id } });
  }

  async deleteBusinessIncome(sub: string, id: string) {
    const ds = await this.ds(sub);
    await ds.getRepository(MemberBusinessIncome).softDelete(id);
    return { id };
  }

  async bulkSaveBusinessIncomes(sub: string, memberId: string, items: any[]) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberBusinessIncome);
    await r.delete({ memberId });
    const saved = [];
    for (const i of items) { saved.push(await r.save(r.create({ ...i, memberId }))); }
    return saved;
  }

  async getFinancials(sub: string, memberId: string) {
    const ds = await this.ds(sub);
    return ds.getRepository(MemberFinancial).find({ where: { memberId }, order: { createdAt: 'ASC' } });
  }

  async addFinancial(sub: string, memberId: string, dto: any) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberFinancial);
    return r.save(r.create({ ...dto, memberId }));
  }

  async updateFinancial(sub: string, id: string, dto: any) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberFinancial);
    const item = await r.findOne({ where: { id } });
    if (!item) throw new NotFoundException('Financial record not found');
    await r.update(id, dto);
    return r.findOne({ where: { id } });
  }

  async deleteFinancial(sub: string, id: string) {
    const ds = await this.ds(sub);
    await ds.getRepository(MemberFinancial).softDelete(id);
    return { id };
  }

  async bulkSaveFinancials(sub: string, memberId: string, items: any[]) {
    const ds = await this.ds(sub);
    const r = ds.getRepository(MemberFinancial);
    await r.delete({ memberId });
    const saved = [];
    for (const i of items) { saved.push(await r.save(r.create({ ...i, memberId }))); }
    return saved;
  }

  async getMemberFullProfile(sub: string, memberId: string) {
    const ds = await this.ds(sub);
    const [incomes, businessIncomes, financials] = await Promise.all([
      ds.getRepository(MemberIncome).find({ where: { memberId } }),
      ds.getRepository(MemberBusinessIncome).find({ where: { memberId } }),
      ds.getRepository(MemberFinancial).find({ where: { memberId } }),
    ]);
    return { incomes, businessIncomes, financials };
  }
}
