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

const create = async (project) => {
  const db = await getDb();
  const {
    job_no, project_name,
    contract_date, due_date,
    delivery_method, site, pm,
    is_active = true,
    project_status = 'active',
    completed_date = null
  } = project;

  const [result] = await db.query(
    `INSERT INTO projects
     (job_no, project_name, contract_date, due_date, delivery_method, site, pm, is_active, project_status, completed_date)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [job_no, project_name, contract_date, due_date, delivery_method, site, pm, is_active, project_status, completed_date]
  );

  return result.insertId;
};

const getAll = async () => {
  const db = await getDb();
  const [rows] = await db.query(
    `SELECT project_id, job_no, project_name, contract_date, due_date, delivery_method, site, pm, is_active, project_status, completed_date, created_at, updated_at FROM projects ORDER BY project_id DESC`
  );
  return rows;
};

// 활성 프로젝트만 조회 (작업보고서용)
const getActiveProjects = async () => {
  const db = await getDb();
  const [rows] = await db.query(
    `SELECT project_id, job_no, project_name, contract_date, due_date, delivery_method, site, pm, is_active, project_status, completed_date, created_at, updated_at FROM projects
     WHERE is_active = TRUE
     ORDER BY project_name ASC`
  );
  return rows;
};

const getById = async (project_id) => {
  const db = await getDb();
  const [rows] = await db.query(
    `SELECT project_id, job_no, project_name, contract_date, due_date, delivery_method, site, pm, is_active, project_status, completed_date, created_at, updated_at FROM projects WHERE project_id = ?`,
    [project_id]
  );
  return rows[0];
};

const update = async (project) => {
  const db = await getDb();
  const {
    project_id, job_no, project_name,
    contract_date, due_date,
    delivery_method, site, pm,
    is_active, project_status, completed_date
  } = project;

  const [result] = await db.query(
    `UPDATE projects
     SET job_no         = ?,
         project_name   = ?,
         contract_date  = ?,
         due_date       = ?,
         delivery_method= ?,
         site           = ?,
         pm             = ?,
         is_active      = ?,
         project_status = ?,
         completed_date = ?
     WHERE project_id = ?`,
    [job_no, project_name, contract_date, due_date, delivery_method, site, pm, is_active, project_status, completed_date, project_id]
  );

  return result.affectedRows;
};

const remove = async (project_id) => {
  const db = await getDb();
  const [result] = await db.query(
    `DELETE FROM projects WHERE project_id = ?`,
    [project_id]
  );
  return result.affectedRows;
};

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