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

// 1. CREATE: 단일 또는 다중 등록 (worker_id 배열 지원)
exports.createDailyIssueReport = async (req, res) => {
  try {
    const body = req.body;

    // 기본 필드
    const base = {
      date: body.date,
      project_id: body.project_id,
      start_time: body.start_time,
      end_time: body.end_time,
      issue_type_id: body.issue_type_id
    };

    if (!base.date || !base.project_id || !base.start_time || !base.end_time || !base.issue_type_id || !body.worker_id) {
      return res.status(400).json({ error: '필수 필드 누락' });
    }

    // worker_id 배열화
    const workers = Array.isArray(body.worker_id) ? body.worker_id : [body.worker_id];
    const insertedIds = [];

    for (const wid of workers) {
      const payload = { ...base, worker_id: wid };

      const insertId = await new Promise((resolve, reject) => {
        dailyIssueReportModel.create(payload, (err, id) => {
          if (err) reject(err);
          else resolve(id);
        });
      });

      insertedIds.push(insertId);
    }

    res.json({ success: true, issue_report_ids: insertedIds });
  } catch (err) {
    console.error('🔥 createDailyIssueReport error:', err);
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 2. READ BY DATE
exports.getDailyIssuesByDate = async (req, res) => {
  try {
    const { date } = req.query;
    const rows = await new Promise((resolve, reject) => {
      dailyIssueReportModel.getAllByDate(date, (err, data) => {
        if (err) reject(err);
        else resolve(data);
      });
    });
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 3. READ ONE
exports.getDailyIssueById = async (req, res) => {
  try {
    const { id } = req.params;
    const row = await new Promise((resolve, reject) => {
      dailyIssueReportModel.getById(id, (err, data) => {
        if (err) reject(err);
        else resolve(data);
      });
    });
    if (!row) return res.status(404).json({ error: 'DailyIssueReport not found' });
    res.json(row);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 4. UPDATE
exports.updateDailyIssue = async (req, res) => {
  try {
    const { id } = req.params;
    const changes = await new Promise((resolve, reject) => {
      dailyIssueReportModel.update(id, req.body, (err, affectedRows) => {
        if (err) reject(err);
        else resolve(affectedRows);
      });
    });
    if (changes === 0) return res.status(404).json({ error: 'No changes or not found' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 5. DELETE
exports.removeDailyIssue = async (req, res) => {
  try {
    const { id } = req.params;
    const changes = await new Promise((resolve, reject) => {
      dailyIssueReportModel.remove(id, (err, affectedRows) => {
        if (err) reject(err);
        else resolve(affectedRows);
      });
    });
    if (changes === 0) return res.status(404).json({ error: 'DailyIssueReport not found' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};