const { getDb } = require('../dbPool');

/**
 * 1. 여러 건 등록 (트랜잭션 사용)
 */
const createBatch = async (reports, callback) => {
  const db = await getDb();
  const conn = await db.getConnection();

  try {
    await conn.beginTransaction();

    const sql = `
      INSERT INTO WorkReports
        (\`date\`, worker_id, project_id, task_id, overtime_hours, work_details, memo)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;

    for (const rpt of reports) {
      const params = [
        rpt.date,
        rpt.worker_id,
        rpt.project_id,
        rpt.task_id || null,
        rpt.overtime_hours || null,
        rpt.work_details || null,
        rpt.memo || null
      ];
      await conn.query(sql, params);
    }

    await conn.commit();
    callback(null);
  } catch (err) {
    await conn.rollback();
    callback(err);
  } finally {
    conn.release();
  }
};

/**
 * 2. 단일 등록
 */
const create = async (report, callback) => {
  try {
    const db = await getDb();
    const {
      date, worker_id, project_id,
      task_id, overtime_hours,
      work_details, memo
    } = report;

    const [result] = await db.query(
      `INSERT INTO WorkReports
       (\`date\`, worker_id, project_id, task_id, overtime_hours, work_details, memo)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        date,
        worker_id,
        project_id,
        task_id || null,
        overtime_hours || null,
        work_details || null,
        memo || null
      ]
    );

    callback(null, result.insertId);
  } catch (err) {
    callback(err);
  }
};

 /**
  * 3. 날짜별 조회
  */
 const getAllByDate = async (date, callback) => {
   try {
     const db = await getDb();
     const sql = `
       SELECT 
         wr.worker_id,               -- 이 줄을 추가했습니다
         wr.id,
         wr.\`date\`,
         w.worker_name,
         p.project_name,
         CONCAT(t.category, ':', t.subcategory) AS task_name,
         wr.overtime_hours,
         wr.work_details,
         wr.memo
       FROM WorkReports wr
       LEFT JOIN Workers w  ON wr.worker_id  = w.worker_id
       LEFT JOIN Projects p ON wr.project_id = p.project_id
       LEFT JOIN Tasks t    ON wr.task_id    = t.task_id
       WHERE wr.\`date\` = ?
       ORDER BY w.worker_name ASC
     `;
     const [rows] = await db.query(sql, [date]);
     callback(null, rows);
   } catch (err) {
     callback(err);
   }
 };

/**
 * 4. 기간 조회
 */
const getByRange = async (start, end, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM WorkReports
       WHERE \`date\` BETWEEN ? AND ?
       ORDER BY \`date\` ASC`,
      [start, end]
    );
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

/**
 * 5. ID로 조회
 */
const getById = async (id, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM WorkReports WHERE id = ?`,
      [id]
    );
    callback(null, rows[0]);
  } catch (err) {
    callback(err);
  }
};

/**
 * 6. 수정
 */
const update = async (id, report, callback) => {
  try {
    const db = await getDb();
    const {
      date, worker_id, project_id,
      task_id, overtime_hours,
      work_details, memo
    } = report;

    const [result] = await db.query(
      `UPDATE WorkReports
       SET \`date\`         = ?,
           worker_id       = ?,
           project_id      = ?,
           task_id         = ?,
           overtime_hours  = ?,
           work_details    = ?,
           memo            = ?,
           updated_at      = CURRENT_TIMESTAMP
       WHERE id = ?`,
      [
        date,
        worker_id,
        project_id,
        task_id || null,
        overtime_hours || null,
        work_details || null,
        memo || null,
        id
      ]
    );

    callback(null, result.affectedRows);
  } catch (err) {
    callback(err);
  }
};

/**
 * 7. 삭제
 */
const remove = async (id, callback) => {
  try {
    const db = await getDb();
    const [result] = await db.query(
      `DELETE FROM WorkReports WHERE id = ?`,
      [id]
    );
    callback(null, result.affectedRows);
  } catch (err) {
    callback(new Error(err.message || String(err)));
  }
};

/**
 * 8. 중복 확인
 */
const existsByDateAndWorker = async (date, worker_id, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT 1 FROM WorkReports WHERE \`date\` = ? AND worker_id = ? LIMIT 1`,
      [date, worker_id]
    );
    callback(null, rows.length > 0);
  } catch (err) {
    callback(err);
  }
};

// ✅ 내보내기
module.exports = {
  create,
  createBatch,
  getAllByDate,
  getByRange,
  getById,
  update,
  remove,
  existsByDateAndWorker
};