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

const PURPOSE_LABELS = {
  day_labor: '일용공', equipment_repair: '설비수리', inspection: '검사',
  delivery: '납품/배송', safety_audit: '안전점검', client_audit: '고객심사',
  construction: '공사', other: '기타'
};

async function today(req, res) {
  try {
    const [visits, stats] = await Promise.all([
      dailyVisitModel.findToday(),
      dailyVisitModel.getTodayStats()
    ]);
    res.json({ success: true, data: { visits, stats } });
  } catch (err) {
    console.error('Today visits error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

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

async function create(req, res) {
  try {
    const { visitor_name, purpose, company_id, company_name } = req.body;
    if (!visitor_name || !visitor_name.trim()) {
      return res.status(400).json({ success: false, error: '방문자명은 필수입니다' });
    }
    if (!purpose) {
      return res.status(400).json({ success: false, error: '방문 목적은 필수입니다' });
    }
    if (!company_id && (!company_name || !company_name.trim())) {
      return res.status(400).json({ success: false, error: '업체를 선택하거나 업체명을 입력해주세요' });
    }
    const userId = req.user.user_id || req.user.id;
    const visit = await dailyVisitModel.create({ ...req.body, registered_by: userId });
    res.status(201).json({ success: true, data: visit });
  } catch (err) {
    console.error('Visit create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

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

async function checkout(req, res) {
  try {
    const visit = await dailyVisitModel.checkout(req.params.id, req.body.checkout_note);
    if (!visit) return res.status(404).json({ success: false, error: '방문 기록을 찾을 수 없습니다' });
    res.json({ success: true, data: visit });
  } catch (err) {
    console.error('Checkout error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function bulkCheckout(req, res) {
  try {
    const result = await dailyVisitModel.bulkCheckout();
    res.json({ success: true, data: { affected: result.affectedRows } });
  } catch (err) {
    console.error('Bulk checkout error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

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

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

async function exportCsv(req, res) {
  try {
    const rows = await dailyVisitModel.exportCsv(req.query);
    const BOM = '\uFEFF';
    const header = '방문일,업체,방문자,인원,목적,상세,작업장,안전교육,차량번호,체크인,체크아웃,상태,담당부서,비고';
    const lines = rows.map(r => [
      r.visit_date ? String(r.visit_date).substring(0, 10) : '',
      `"${(r.company || '').replace(/"/g, '""')}"`,
      `"${(r.visitor_name || '').replace(/"/g, '""')}"`,
      r.visitor_count || 1,
      PURPOSE_LABELS[r.purpose] || r.purpose,
      `"${(r.purpose_detail || '').replace(/"/g, '""')}"`,
      `"${(r.workplace_name || '').replace(/"/g, '""')}"`,
      r.safety_education_yn ? 'Y' : 'N',
      r.vehicle_number || '',
      r.check_in_time || '',
      r.check_out_time || '',
      r.status,
      r.managing_department || '',
      `"${(r.notes || '').replace(/"/g, '""')}"`
    ].join(','));

    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', 'attachment; filename=visits.csv');
    res.send(BOM + header + '\n' + lines.join('\n'));
  } catch (err) {
    console.error('Export error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

module.exports = { today, list, create, update, checkout, bulkCheckout, deleteVisit, stats, exportCsv };
