/**
 * ServChan-recorded WO close-outs (when SC status API cannot set CONFIRMED).
 */

export function getWoCloseout(db, workOrderId) {
  return new Promise((resolve, reject) => {
    db.get(
      `SELECT workOrderId, confirmedAt, confirmedBy, scStatusUpdated, noteText
       FROM wo_closeouts WHERE workOrderId = ?`,
      [workOrderId],
      (err, row) => (err ? reject(err) : resolve(row || null))
    );
  });
}

export function saveWoCloseout(db, { workOrderId, confirmedBy, scStatusUpdated, noteText }) {
  return new Promise((resolve, reject) => {
    db.run(
      `INSERT OR REPLACE INTO wo_closeouts (workOrderId, confirmedAt, confirmedBy, scStatusUpdated, noteText)
       VALUES (?, ?, ?, ?, ?)`,
      [
        workOrderId,
        new Date().toISOString(),
        confirmedBy,
        scStatusUpdated ? 1 : 0,
        noteText ?? null,
      ],
      (err) => (err ? reject(err) : resolve())
    );
  });
}

export async function hasWoCloseout(db, workOrderId) {
  const row = await getWoCloseout(db, workOrderId);
  return Boolean(row);
}

export default { getWoCloseout, saveWoCloseout, hasWoCloseout };
