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

/**
 * 1. 여러 개의 이슈 보고서를 트랜잭션으로 생성합니다.
 */
const createMany = async (reports) => {
  const db = await getDb();
  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();

    const insertedIds = [];
    const sql = `
      INSERT INTO DailyIssueReports
      (date, user_id, project_id, start_time, end_time, issue_type_id)
      VALUES (?, ?, ?, ?, ?, ?)
    `;

    for (const report of reports) {
      const { date, user_id, project_id, start_time, end_time, issue_type_id } = report;
      const [result] = await conn.query(sql, [date, user_id, project_id, start_time, end_time, issue_type_id]);
      insertedIds.push(result.insertId);
    }

    await conn.commit();
    return insertedIds;
  } catch (err) {
    await conn.rollback();
    console.error('[Model] 여러 이슈 보고서 생성 중 오류:', err);
    throw new Error('데이터베이스에 이슈 보고서를 생성하는 중 오류가 발생했습니다.');
  } finally {
    conn.release();
  }
};

/**
 * 2. 특정 날짜의 전체 이슈 목록 조회
 */
const getAllByDate = async (date) => {
  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.user_id = w.user_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]
  );
  return rows;
};

/**
 * 3. 단일 조회
 */
const getById = async (id) => {
  const db = await getDb();
  const [rows] = await db.query(`SELECT id, date, user_id, project_id, issue_type_id, description, created_at, start_time, end_time FROM DailyIssueReports WHERE id = ?`, [id]);
  return rows[0];
};

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

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

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

  values.push(id);

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

  return result.affectedRows;
};

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

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