const pool = require("../../../../managers/dbConfig");
const { getFormattedDateTime } = require("../../../../managers/formatDateTime");

class LabResult {
  // ✅ Save Lab Results w
  static async saveLabResults({
    pt_id,
    signed_by,
    specimen,
    comment,
    request_id,
    results,
  }) {
    if (!pt_id) throw "Patient ID is required!";
    //  if(!specimen) throw `specimen is required for ${specimen}`;
    if (!signed_by) throw "Staff Identity can NOT be ascertained. Try Re-login";
    if (!request_id) throw "Request ID is required!";

    const connection = await pool.getConnection(); // ✅ Get a connection for transaction
    await connection.beginTransaction(); // ✅ Start Transaction

    // Insert into `lab_results`
    const [result] = await connection.execute(
      "INSERT INTO lab_results (pt_id,request_id, signed_by, specimen, comment) VALUES (?, ?, ?, ?,?)",
      [pt_id, request_id, signed_by, specimen, comment]
    );
    console.log(result);

    const resultId = result.insertId;

    // Prepare dynamic test results for bulk insert
    const values = [];
    for (const section in results) {
      for (const field in results[section]) {
        values.push([resultId, section, field, results[section][field]]);
      }
    }

    if (values.length > 0) {
      await connection.query(
        "INSERT INTO lab_results_fileds (result_id, test_category, test_name, value) VALUES ?",
        [values]
      );
    }

    await connection.commit(); // ✅ Commit transaction if everything succeeds
    connection.release(); // ✅ Release connection

    return { resultId, pt_id, signed_by, specimen };
  }
}

module.exports = LabResult;
