import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, IsNull } from 'typeorm';
import { FarmModel } from './entities/farm.entity';
import { GenomeRequestModel } from '../genome/entities/genome-request.entity';
import { CowModel } from '../cow/entities/cow.entity';
import { isValidGenomeAnalysis, VALID_CHIP_SIRE_NAME } from '../common/config/GenomeAnalysisConfig';

@Injectable()
export class FarmService {
  constructor(
    @InjectRepository(FarmModel)
    private readonly farmRepository: Repository<FarmModel>,

    @InjectRepository(GenomeRequestModel)
    private readonly genomeRequestRepository: Repository<GenomeRequestModel>,

    @InjectRepository(CowModel)
    private readonly cowRepository: Repository<CowModel>,
  ) { }

  // 전체 농장 조회
  async findAll(): Promise<FarmModel[]> {
    return this.farmRepository.find({
      where: { delDt: IsNull() },
      relations: ['user'],
      order: { regDt: 'DESC' },
    });
  }

  // 사용자별 농장 조회
  async findByUserId(userNo: number): Promise<FarmModel[]> {
    return this.farmRepository.find({
      where: { fkUserNo: userNo, delDt: IsNull() },
      relations: ['user'],
      order: { regDt: 'DESC' },
    });
  }

  // 농장 단건 조회
  async findOne(id: number): Promise<FarmModel> {
    const farm = await this.farmRepository.findOne({
      where: { pkFarmNo: id, delDt: IsNull() },
      relations: ['user'],
    });
    if (!farm) {
      throw new NotFoundException('Farm #' + id + ' not found');
    }
    return farm;
  }

  // 농장 생성
  async create(data: Partial<FarmModel>): Promise<FarmModel> {
    const farm = this.farmRepository.create(data);
    return this.farmRepository.save(farm);
  }

  // 농장 수정
  async update(id: number, data: Partial<FarmModel>): Promise<FarmModel> {
    await this.findOne(id);
    await this.farmRepository.update(id, data);
    return this.findOne(id);
  }

  // 농장 삭제
  async remove(id: number): Promise<void> {
    const farm = await this.findOne(id);
    await this.farmRepository.softRemove(farm);
  }

  // 농장 최신 분석 의뢰 정보 조회
  async getLatestAnalysisRequest(farmNo: number): Promise<any> {
    const farm = await this.findOne(farmNo);

    const requests = await this.genomeRequestRepository.find({
      where: { fkFarmNo: farmNo, delDt: IsNull() },
      relations: ['cow'],
      order: { requestDt: 'DESC' },
    });

    const cows = await this.cowRepository.find({
      where: { fkFarmNo: farmNo, delDt: IsNull() },
    });

    const farmAnlysCnt = requests.length;
    const matchCnt = requests.filter(r => isValidGenomeAnalysis(r.chipSireName, r.chipDamName, r.cow?.cowId)).length;
    const failCnt = requests.filter(r => r.chipSireName && r.chipSireName !== '일치').length;
    const noHistCnt = requests.filter(r => !r.chipSireName).length;

    return {
      pkFarmAnlysNo: 1,
      fkFarmNo: farmNo,
      farmAnlysNm: farm.farmerName,
      anlysReqDt: requests[0]?.requestDt || new Date(),
      region: farm.regionSi,
      city: farm.regionGu,
      anlysReqCnt: cows.length,
      farmAnlysCnt,
      matchCnt,
      mismatchCnt: failCnt,
      failCnt,
      noHistCnt,
      matchRate: farmAnlysCnt > 0 ? Math.round((matchCnt / farmAnlysCnt) * 100) : 0,
      msAnlysCnt: 0,
      anlysRmrk: '',
      paternities: requests.map(r => ({
        pkFarmPaternityNo: r.pkRequestNo,
        fkFarmAnlysNo: 1,
        receiptDate: r.requestDt,
        farmOwnerName: farm.farmerName,
        individualNo: r.cow?.cowId || '',
        kpnNo: r.cow?.sireKpn || '',
        motherIndividualNo: r.cow?.damCowId || '',
        hairRootQuality: r.sampleAmount || '',
        remarks: r.cowRemarks || '',
        fatherMatch: r.chipSireName === '일치' ? '일치' : (r.chipSireName ? '불일치' : '미확인'),
        motherMatch: r.chipDamName || '미확인',
        reportDate: r.chipReportDt,
      })),
    };
  }

  // 농장 전체 분석 의뢰 목록 조회
  async getAllAnalysisRequests(farmNo: number): Promise<any[]> {
    const latestRequest = await this.getLatestAnalysisRequest(farmNo);
    return [latestRequest];
  }
}
