const educationModel = require('../models/educationModel');

async function list(req, res) {
  try {
    const rows = await educationModel.findAll(req.query);
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Education list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function getById(req, res) {
  try {
    const row = await educationModel.findById(req.params.id);
    if (!row) return res.status(404).json({ success: false, error: '교육 기록을 찾을 수 없습니다' });
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Education getById error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function create(req, res) {
  try {
    const { education_date } = req.body;
    if (!education_date) {
      return res.status(400).json({ success: false, error: '교육일은 필수입니다' });
    }
    const userId = req.user.user_id || req.user.id;
    const report = await educationModel.create({ ...req.body, registered_by: userId });
    res.status(201).json({ success: true, data: report });
  } catch (err) {
    console.error('Education create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function update(req, res) {
  try {
    const report = await educationModel.update(req.params.id, req.body);
    if (!report) return res.status(404).json({ success: false, error: '교육 기록을 찾을 수 없습니다' });
    res.json({ success: true, data: report });
  } catch (err) {
    console.error('Education update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function deleteReport(req, res) {
  try {
    await educationModel.deleteReport(req.params.id);
    res.json({ success: true, message: '삭제 완료' });
  } catch (err) {
    console.error('Education delete error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function stats(req, res) {
  try {
    const data = await educationModel.getStats(req.query);
    res.json({ success: true, data });
  } catch (err) {
    console.error('Education stats error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

module.exports = { list, getById, create, update, deleteReport, stats };
