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

function buildWhereClause({ company, company_id, date_from, date_to, status, project_id }) {
  let where = ' WHERE 1=1';
  const params = [];
  if (company) { where += ' AND pc.company_name LIKE ?'; params.push('%' + company + '%'); }
  if (company_id) { where += ' AND ps.company_id = ?'; params.push(company_id); }
  if (date_from) { where += ' AND ps.end_date >= ?'; params.push(date_from); }
  if (date_to) { where += ' AND ps.start_date <= ?'; params.push(date_to); }
  if (status) { where += ' AND ps.status = ?'; params.push(status); }
  if (project_id) { where += ' AND ps.project_id = ?'; params.push(project_id); }
  return { where, params };
}

async function findAll({ company, company_id, date_from, date_to, status, project_id, page = 1, limit = 50 } = {}) {
  const db = getPool();
  const { where, params } = buildWhereClause({ company, company_id, date_from, date_to, status, project_id });

  const fromClause = ` FROM partner_schedules ps
             LEFT JOIN partner_companies pc ON ps.company_id = pc.id
             LEFT JOIN sso_users su ON ps.registered_by = su.user_id
             LEFT JOIN projects p ON ps.project_id = p.project_id`;

  const [countResult] = await db.query('SELECT COUNT(*) AS cnt' + fromClause + where, params);

  let sql = `SELECT ps.*, pc.company_name, su.name AS registered_by_name,
                    p.project_name, p.job_no` + fromClause + where;
  sql += ' ORDER BY ps.start_date DESC, ps.created_at DESC';
  const offset = (page - 1) * limit;
  sql += ' LIMIT ? OFFSET ?';
  const [rows] = await db.query(sql, [...params, limit, offset]);
  return { rows, total: countResult[0].cnt };
}

async function findById(id) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT ps.*, pc.company_name, su.name AS registered_by_name,
            p.project_name, p.job_no
     FROM partner_schedules ps
     LEFT JOIN partner_companies pc ON ps.company_id = pc.id
     LEFT JOIN sso_users su ON ps.registered_by = su.user_id
     LEFT JOIN projects p ON ps.project_id = p.project_id
     WHERE ps.id = ?`, [id]);
  return rows[0] || null;
}

async function findByCompanyToday(companyId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT ps.*, pc.company_name, p.project_name, p.job_no
     FROM partner_schedules ps
     LEFT JOIN partner_companies pc ON ps.company_id = pc.id
     LEFT JOIN projects p ON ps.project_id = p.project_id
     WHERE ps.company_id = ? AND ps.start_date <= CURDATE() AND ps.end_date >= CURDATE()
       AND ps.status NOT IN ('cancelled','rejected','requested')
     ORDER BY ps.created_at DESC`, [companyId]);
  return rows;
}

async function findRequestsByCompany(companyId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT ps.*, pc.company_name, su.name AS requested_by_name
     FROM partner_schedules ps
     LEFT JOIN partner_companies pc ON ps.company_id = pc.id
     LEFT JOIN sso_users su ON ps.requested_by = su.user_id
     WHERE ps.company_id = ? AND ps.status IN ('requested','rejected')
     ORDER BY ps.created_at DESC`, [companyId]);
  return rows;
}

async function findByProject(projectId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT ps.*, pc.company_name
     FROM partner_schedules ps
     LEFT JOIN partner_companies pc ON ps.company_id = pc.id
     WHERE ps.project_id = ?
     ORDER BY ps.start_date, pc.company_name`, [projectId]);
  return rows;
}

async function create(data) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO partner_schedules (company_id, project_id, start_date, end_date, work_description, workplace_name, expected_workers, registered_by, requested_by, status, notes)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [data.company_id, data.project_id || null,
     data.start_date, data.end_date || data.start_date,
     data.work_description || null,
     data.workplace_name || null, data.expected_workers || null,
     data.registered_by || null, data.requested_by || null,
     data.status || 'scheduled', data.notes || null]);
  return findById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];
  if (data.company_id !== undefined) { fields.push('company_id = ?'); values.push(data.company_id); }
  if (data.project_id !== undefined) { fields.push('project_id = ?'); values.push(data.project_id || null); }
  if (data.start_date !== undefined) { fields.push('start_date = ?'); values.push(data.start_date); }
  if (data.end_date !== undefined) { fields.push('end_date = ?'); values.push(data.end_date); }
  if (data.work_description !== undefined) { fields.push('work_description = ?'); values.push(data.work_description || null); }
  if (data.workplace_name !== undefined) { fields.push('workplace_name = ?'); values.push(data.workplace_name || null); }
  if (data.expected_workers !== undefined) { fields.push('expected_workers = ?'); values.push(data.expected_workers || null); }
  if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }
  if (data.status !== undefined) { fields.push('status = ?'); values.push(data.status); }
  if (fields.length === 0) return findById(id);
  values.push(id);
  await db.query(`UPDATE partner_schedules SET ${fields.join(', ')} WHERE id = ?`, values);
  return findById(id);
}

async function updateStatus(id, status) {
  const db = getPool();
  await db.query('UPDATE partner_schedules SET status = ? WHERE id = ?', [status, id]);
  return findById(id);
}

async function deleteSchedule(id) {
  const schedule = await findById(id);
  if (!schedule) return null;

  const db = getPool();
  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();
    await conn.query('DELETE FROM partner_work_reports WHERE schedule_id = ?', [id]);
    await conn.query('DELETE FROM partner_work_checkins WHERE schedule_id = ?', [id]);
    await conn.query("DELETE FROM safety_education_reports WHERE target_type = 'partner_schedule' AND target_id = ?", [id]);
    await conn.query('DELETE FROM partner_schedules WHERE id = ?', [id]);
    await conn.commit();
    return true;
  } catch (err) {
    await conn.rollback();
    throw err;
  } finally {
    conn.release();
  }
}

async function findActiveByCompany(companyId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT ps.*, pc.company_name, p.project_name, p.job_no
     FROM partner_schedules ps
     LEFT JOIN partner_companies pc ON ps.company_id = pc.id
     LEFT JOIN projects p ON ps.project_id = p.project_id
     WHERE ps.company_id = ?
       AND ps.status NOT IN ('cancelled','rejected','requested','completed')
     ORDER BY ps.start_date ASC, ps.created_at DESC`, [companyId]);
  return rows;
}

module.exports = { findAll, findById, findByCompanyToday, findActiveByCompany, findRequestsByCompany, findByProject, create, update, updateStatus, deleteSchedule };
