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

async function findAll({ date_from, date_to, target_type, status, page = 1, limit = 50 } = {}) {
  const db = getPool();
  let sql = 'SELECT * FROM safety_education_reports WHERE 1=1';
  const params = [];
  if (date_from) { sql += ' AND education_date >= ?'; params.push(date_from); }
  if (date_to) { sql += ' AND education_date <= ?'; params.push(date_to); }
  if (target_type) { sql += ' AND target_type = ?'; params.push(target_type); }
  if (status) { sql += ' AND status = ?'; params.push(status); }
  sql += ' ORDER BY education_date 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 * FROM safety_education_reports WHERE id = ?', [id]);
  return rows[0] || null;
}

async function create(data) {
  const db = getPool();
  const attendeesStr = data.attendees ? (typeof data.attendees === 'string' ? data.attendees : JSON.stringify(data.attendees)) : null;
  const [result] = await db.query(
    `INSERT INTO safety_education_reports (target_type, target_id, education_date, educator, attendees, status, notes, registered_by)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
    [data.target_type, data.target_id || null, data.education_date, data.educator || null,
     attendeesStr, data.status || 'planned', data.notes || null, data.registered_by]
  );
  return findById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];
  if (data.target_type !== undefined) { fields.push('target_type = ?'); values.push(data.target_type); }
  if (data.education_date !== undefined) { fields.push('education_date = ?'); values.push(data.education_date); }
  if (data.educator !== undefined) { fields.push('educator = ?'); values.push(data.educator || null); }
  if (data.attendees !== undefined) {
    const attendeesStr = data.attendees ? (typeof data.attendees === 'string' ? data.attendees : JSON.stringify(data.attendees)) : null;
    fields.push('attendees = ?');
    values.push(attendeesStr);
  }
  if (data.status !== undefined) { fields.push('status = ?'); values.push(data.status); }
  if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }
  if (fields.length === 0) return findById(id);
  values.push(id);
  await db.query(`UPDATE safety_education_reports SET ${fields.join(', ')} WHERE id = ?`, values);
  return findById(id);
}

async function deleteReport(id) {
  const db = getPool();
  await db.query('DELETE FROM safety_education_reports WHERE id = ?', [id]);
}

async function getStats({ date_from, date_to } = {}) {
  const db = getPool();
  const params = [];
  let dateFilter = '';
  if (date_from) { dateFilter += ' AND education_date >= ?'; params.push(date_from); }
  if (date_to) { dateFilter += ' AND education_date <= ?'; params.push(date_to); }

  const [rows] = await db.query(
    `SELECT target_type, COUNT(*) AS cnt,
       SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed,
       SUM(CASE WHEN status = 'planned' THEN 1 ELSE 0 END) AS planned,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
     FROM safety_education_reports WHERE 1=1 ${dateFilter} GROUP BY target_type`,
    params
  );
  return rows;
}

module.exports = { findAll, findById, create, update, deleteReport, getStats };
