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

/**
 * 1. 등록 (단일 레코드)
 */
const create = async (report, callback) => {
  try {
    const db = await getDb();
    const {
      date,
      worker_id,
      project_id,
      start_time,
      end_time,
      issue_type_id,
      description = null // 선택값 처리
    } = report;

    const [result] = await db.query(
      `INSERT INTO DailyIssueReports 
       (date, worker_id, project_id, start_time, end_time, issue_type_id, description)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [date, worker_id, project_id, start_time, end_time, issue_type_id, description]
    );

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

/**
 * 2. 특정 날짜의 전체 이슈 목록 조회
 */
const getAllByDate = async (date, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT 
        d.id,
        d.date,
        w.worker_name,
        p.project_name,
        d.start_time,
        d.end_time,
        t.category,
        t.subcategory,
        d.description
       FROM DailyIssueReports d
       LEFT JOIN Workers w ON d.worker_id = w.worker_id
       LEFT JOIN Projects p ON d.project_id = p.project_id
       LEFT JOIN IssueTypes t ON d.issue_type_id = t.issue_type_id
       WHERE d.date = ?
       ORDER BY d.start_time ASC`,
      [date]
    );
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

/**
 * 3. 단일 조회 (선택사항: 컨트롤러에서 사용 중)
 */
const getById = async (id, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(`SELECT * FROM DailyIssueReports WHERE id = ?`, [id]);
    callback(null, rows[0]);
  } catch (err) {
    callback(err);
  }
};

/**
 * 4. 수정
 */
const update = async (id, data, callback) => {
  try {
    const db = await getDb();

    const fields = [];
    const values = [];

    for (const key in data) {
      fields.push(`${key} = ?`);
      values.push(data[key]);
    }

    values.push(id); // 마지막에 id

    const [result] = await db.query(
      `UPDATE DailyIssueReports SET ${fields.join(', ')} WHERE id = ?`,
      values
    );

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

/**
 * 5. 삭제
 */
const remove = async (id, callback) => {
  try {
    const db = await getDb();
    const [result] = await db.query(`DELETE FROM DailyIssueReports WHERE id = ?`, [id]);
    callback(null, result.affectedRows);
  } catch (err) {
    callback(err);
  }
};

module.exports = {
  create,
  getAllByDate,
  getById,
  update,
  remove
};