const checkinModel = require('../models/checkinModel');
const workReportModel = require('../models/workReportModel');
const scheduleModel = require('../models/scheduleModel');

// 일정별 체크인 목록
async function list(req, res) {
  try {
    const rows = await checkinModel.findBySchedule(req.params.scheduleId);
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Checkin list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 내 체크인 (협력업체 포탈 - 오늘)
async function myCheckins(req, res) {
  try {
    const companyId = req.user.partner_company_id;
    if (!companyId) {
      return res.status(403).json({ success: false, error: '협력업체 계정이 아닙니다' });
    }
    const rows = await checkinModel.findActiveByCompany(companyId);
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Checkin myCheckins error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 체크인
async function checkIn(req, res) {
  try {
    const { schedule_id, company_id, worker_names, actual_worker_count } = req.body;
    if (!schedule_id) {
      return res.status(400).json({ success: false, error: '일정을 선택해주세요' });
    }
    const resolvedCompanyId = company_id || req.user.partner_company_id;
    if (!resolvedCompanyId) {
      return res.status(400).json({ success: false, error: '업체 정보가 필요합니다' });
    }
    // 일정 유효성 검증
    const schedule = await scheduleModel.findById(schedule_id);
    if (!schedule) {
      return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
    }
    if (['cancelled', 'rejected', 'completed'].includes(schedule.status)) {
      return res.status(400).json({ success: false, error: '마감되었거나 취소된 일정입니다' });
    }
    const data = {
      schedule_id,
      company_id: resolvedCompanyId,
      checked_by: req.user.user_id || req.user.id,
      worker_names,
      actual_worker_count,
      notes: req.body.notes
    };
    const row = await checkinModel.checkIn(data);
    res.status(201).json({ success: true, data: row });
  } catch (err) {
    console.error('Checkin checkIn error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 체크아웃
async function checkOut(req, res) {
  try {
    const reports = await workReportModel.findByCheckin(req.params.id);
    if (!reports || reports.length === 0) {
      return res.status(400).json({ success: false, error: '업무현황을 먼저 입력해주세요' });
    }
    const row = await checkinModel.checkOut(req.params.id);
    if (!row) return res.status(404).json({ success: false, error: '체크인 기록을 찾을 수 없습니다' });
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Checkin checkOut error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 체크인 정보 수정
async function update(req, res) {
  try {
    const row = await checkinModel.update(req.params.id, req.body);
    if (!row) return res.status(404).json({ success: false, error: '체크인 기록을 찾을 수 없습니다' });
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Checkin update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 대시보드 통계
async function stats(req, res) {
  try {
    const activeCount = await checkinModel.countActive();
    res.json({ success: true, total: activeCount });
  } catch (err) {
    console.error('Checkin stats error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 체크인 삭제
async function deleteCheckin(req, res) {
  try {
    const result = await checkinModel.deleteCheckin(req.params.id);
    if (!result) return res.status(404).json({ success: false, error: '체크인 기록을 찾을 수 없습니다' });
    res.json({ success: true });
  } catch (err) {
    console.error('Checkin delete error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 체크아웃 + 보고 통합 (협력업체 포탈 전용)
async function checkOutWithReport(req, res) {
  try {
    const checkinId = parseInt(req.params.id);
    const checkin = await checkinModel.findById(checkinId);
    if (!checkin) return res.status(404).json({ success: false, error: '체크인 기록을 찾을 수 없습니다' });

    // 소유권 검증: 협력업체 본인 체크인만 가능
    const companyId = req.user.partner_company_id;
    if (companyId && checkin.company_id !== companyId) {
      return res.status(403).json({ success: false, error: '권한이 없습니다' });
    }

    // schedule에서 work_description 가져오기
    let workContent = '작업 완료';
    if (checkin.schedule_id) {
      const schedule = await scheduleModel.findById(checkin.schedule_id);
      if (schedule && schedule.work_description) {
        workContent = schedule.work_description;
      }
    }

    const reportData = {
      reporter_id: req.user.user_id || req.user.id,
      workers: req.body.workers || [],
      work_content: workContent
    };

    const row = await checkinModel.checkOutWithReport(checkinId, reportData);
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Checkin checkOutWithReport error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업 이력 (협력업체 포탈)
async function myHistory(req, res) {
  try {
    const companyId = req.user.partner_company_id;
    if (!companyId) {
      return res.status(403).json({ success: false, error: '협력업체 계정이 아닙니다' });
    }
    const { date_from, date_to, page, limit } = req.query;
    const result = await checkinModel.findHistoryByCompany(companyId, {
      dateFrom: date_from, dateTo: date_to,
      page: parseInt(page) || 1, limit: parseInt(limit) || 20
    });
    res.json({ success: true, ...result });
  } catch (err) {
    console.error('Checkin myHistory error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

module.exports = { list, myCheckins, checkIn, checkOut, update, stats, deleteCheckin, checkOutWithReport, myHistory };
