import { Injectable, NotFoundException } from '@nestjs/common';
import { MESSAGES } from '../../common/messages.js';
import { PrismaService } from '../../prisma.service.js';
import {
  buildPatientLifecycleRecords,
  PATIENT_LIFECYCLE_INCLUDE,
} from '../patient-lifecycle.util.js';

@Injectable()
export class CPatientsService {
  constructor(private readonly prisma: PrismaService) {}

  async getFamilyLifecycleByAccount(accountId: number) {
    const account = await this.prisma.familyMiniAppAccount.findUnique({
      where: { id: accountId },
      select: {
        id: true,
        phone: true,
      },
    });
    if (!account) {
      throw new NotFoundException(MESSAGES.AUTH.FAMILY_ACCOUNT_NOT_FOUND);
    }

    const patients = await this.prisma.patient.findMany({
      where: {
        phone: account.phone,
      },
      include: PATIENT_LIFECYCLE_INCLUDE,
    });
    if (patients.length === 0) {
      throw new NotFoundException(MESSAGES.PATIENT.LIFE_CYCLE_NOT_FOUND);
    }

    return {
      phone: account.phone,
      patientCount: patients.length,
      lifecycle: buildPatientLifecycleRecords(patients),
    };
  }
}
