const { getPool } = require('./partnerModel');

async function findAll({ status, date_from, date_to, department_id, page = 1, limit = 50 } = {}) {
  const db = getPool();
  let sql = `SELECT dlr.*, su.name AS requester_name, sa.name AS approver_name, d.department_name
             FROM day_labor_requests dlr
             LEFT JOIN sso_users su ON dlr.requester_id = su.user_id
             LEFT JOIN sso_users sa ON dlr.approved_by = sa.user_id
             LEFT JOIN departments d ON dlr.department_id = d.department_id
             WHERE 1=1`;
  const params = [];
  if (status) { sql += ' AND dlr.status = ?'; params.push(status); }
  if (date_from) { sql += ' AND dlr.work_date >= ?'; params.push(date_from); }
  if (date_to) { sql += ' AND dlr.work_date <= ?'; params.push(date_to); }
  if (department_id) { sql += ' AND dlr.department_id = ?'; params.push(department_id); }
  sql += ' ORDER BY dlr.work_date DESC, dlr.created_at DESC';
  const offset = (page - 1) * limit;
  sql += ' LIMIT ? OFFSET ?';
  params.push(limit, offset);
  const [rows] = await db.query(sql, params);
  return rows;
}

async function findById(id) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT dlr.*, su.name AS requester_name, sa.name AS approver_name, d.department_name
     FROM day_labor_requests dlr
     LEFT JOIN sso_users su ON dlr.requester_id = su.user_id
     LEFT JOIN sso_users sa ON dlr.approved_by = sa.user_id
     LEFT JOIN departments d ON dlr.department_id = d.department_id
     WHERE dlr.id = ?`, [id]);
  return rows[0] || null;
}

async function create(data) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO day_labor_requests (requester_id, department_id, work_date, worker_count, work_description, workplace_name, notes)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [data.requester_id, data.department_id || null, data.work_date, data.worker_count || 1,
     data.work_description || null, data.workplace_name || null, data.notes || null]);
  return findById(result.insertId);
}

async function approve(id, approvedBy) {
  const db = getPool();
  await db.query(
    `UPDATE day_labor_requests SET status = 'approved', approved_by = ?, approved_at = NOW() WHERE id = ? AND status = 'pending'`,
    [approvedBy, id]);
  return findById(id);
}

async function reject(id, approvedBy, notes) {
  const db = getPool();
  await db.query(
    `UPDATE day_labor_requests SET status = 'rejected', approved_by = ?, approved_at = NOW(), notes = CONCAT(IFNULL(notes,''), ?, '') WHERE id = ? AND status = 'pending'`,
    [approvedBy, notes ? '\n[거절사유] ' + notes : '', id]);
  return findById(id);
}

async function complete(id) {
  const db = getPool();
  await db.query(`UPDATE day_labor_requests SET status = 'completed' WHERE id = ? AND status = 'approved'`, [id]);
  return findById(id);
}

async function markSafetyReported(id) {
  const db = getPool();
  await db.query(`UPDATE day_labor_requests SET safety_reported = TRUE WHERE id = ?`, [id]);
}

async function getStats({ date_from, date_to } = {}) {
  const db = getPool();
  let dateFilter = '';
  const params = [];
  if (date_from) { dateFilter += ' AND work_date >= ?'; params.push(date_from); }
  if (date_to) { dateFilter += ' AND work_date <= ?'; params.push(date_to); }
  const [rows] = await db.query(
    `SELECT status, COUNT(*) AS cnt, SUM(worker_count) AS total_workers
     FROM day_labor_requests WHERE 1=1 ${dateFilter} GROUP BY status`, params);
  return rows;
}

module.exports = { findAll, findById, create, approve, reject, complete, markSafetyReported, getStats };
