const workReportModel = require('../models/workReportModel');
const checkinModel = require('../models/checkinModel');
const ExcelJS = require('exceljs');
const notify = require('../shared/utils/notifyHelper');

// 작업보고 목록
async function list(req, res) {
  try {
    const { company_id, date_from, date_to, schedule_id, confirmed, page, limit } = req.query;
    const rows = await workReportModel.findAll({
      company_id: company_id ? parseInt(company_id) : undefined,
      date_from,
      date_to,
      schedule_id: schedule_id ? parseInt(schedule_id) : undefined,
      confirmed,
      page: page ? parseInt(page) : 1,
      limit: limit ? parseInt(limit) : 50
    });
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('WorkReport list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업보고 상세
async function getById(req, res) {
  try {
    const row = await workReportModel.findById(req.params.id);
    if (!row) return res.status(404).json({ success: false, error: '작업보고를 찾을 수 없습니다' });
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('WorkReport get error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 내 작업보고 (협력업체 포탈)
async function myReports(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 rows = await workReportModel.findAll({
      company_id: companyId,
      date_from,
      date_to,
      page: page ? parseInt(page) : 1,
      limit: limit ? parseInt(limit) : 50
    });
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('WorkReport myReports error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업보고 등록
async function create(req, res) {
  try {
    const { checkin_id, schedule_id, company_id, report_date, workers } = req.body;

    if (!report_date) {
      return res.status(400).json({ success: false, error: '보고일은 필수입니다' });
    }

    if (!checkin_id) {
      return res.status(400).json({ success: false, error: '체크인 ID는 필수입니다' });
    }

    const checkin = await checkinModel.findById(checkin_id);
    if (!checkin) {
      return res.status(400).json({ success: false, error: '유효하지 않은 체크인 ID입니다' });
    }

    if (schedule_id && checkin.schedule_id !== 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 data = {
      ...req.body,
      company_id: resolvedCompanyId,
      reporter_id: req.user.user_id || req.user.id,
      workers: workers || []
    };
    const row = await workReportModel.create(data);

    // 알림: 작업 보고서 제출
    notify.send({
      type: 'partner_work',
      title: '작업 보고서 제출',
      message: `${report_date} 작업 보고서가 제출되었습니다.`,
      link_url: '/workreport.html',
      reference_type: 'work_reports',
      reference_id: row.id || row.report_id,
      created_by: data.reporter_id
    });

    res.status(201).json({ success: true, data: row });
  } catch (err) {
    console.error('WorkReport create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업보고 수정
async function update(req, res) {
  try {
    const existing = await workReportModel.findById(req.params.id);
    if (!existing) {
      return res.status(404).json({ success: false, error: '작업보고를 찾을 수 없습니다' });
    }

    // 소유권 검증 (협력업체 포탈에서 호출 시)
    if (req.user.partner_company_id && existing.reporter_id !== (req.user.user_id || req.user.id)) {
      return res.status(403).json({ success: false, error: '본인이 작성한 보고만 수정할 수 있습니다' });
    }

    // 확인 완료된 보고 수정 불가 (협력업체만 제한, 구매팀은 수정 가능)
    if (req.user.partner_company_id && existing.confirmed_by) {
      return res.status(400).json({ success: false, error: '확인 완료된 보고는 수정할 수 없습니다' });
    }

    const row = await workReportModel.update(req.params.id, req.body);
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('WorkReport update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업보고 확인
async function confirm(req, res) {
  try {
    const confirmedBy = req.user.user_id || req.user.id;
    const row = await workReportModel.confirm(req.params.id, confirmedBy);
    if (!row) return res.status(404).json({ success: false, error: '작업보고를 찾을 수 없습니다' });
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('WorkReport confirm error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업보고 반려
async function reject(req, res) {
  try {
    const existing = await workReportModel.findById(req.params.id);
    if (!existing) {
      return res.status(404).json({ success: false, error: '작업보고를 찾을 수 없습니다' });
    }
    if (existing.confirmed_by) {
      return res.status(400).json({ success: false, error: '확인된 보고는 반려할 수 없습니다. 먼저 확인 취소하세요' });
    }
    if (existing.rejected_by) {
      return res.status(400).json({ success: false, error: '이미 반려된 보고입니다' });
    }
    const { reason } = req.body;
    if (!reason || !reason.trim()) {
      return res.status(400).json({ success: false, error: '반려 사유를 입력하세요' });
    }
    const rejectedBy = req.user.user_id || req.user.id;
    const row = await workReportModel.reject(req.params.id, rejectedBy, reason.trim());
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('WorkReport reject error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 종합 요약
async function summary(req, res) {
  try {
    const { company_id, schedule_id, date_from, date_to } = req.query;

    if (!date_from || !date_to) {
      return res.status(400).json({ success: false, error: '기간(date_from, date_to)은 필수입니다' });
    }

    // 최대 3개월 검증
    const from = new Date(date_from);
    const to = new Date(date_to);
    const diffMs = to - from;
    if (diffMs < 0) {
      return res.status(400).json({ success: false, error: '시작일이 종료일보다 늦을 수 없습니다' });
    }
    if (diffMs > 92 * 24 * 60 * 60 * 1000) {
      return res.status(400).json({ success: false, error: '조회 기간은 최대 3개월입니다' });
    }

    const rows = await workReportModel.findAllAggregated({
      company_id: company_id ? parseInt(company_id) : undefined,
      schedule_id: schedule_id ? parseInt(schedule_id) : undefined,
      date_from,
      date_to
    });
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('WorkReport summary error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 엑셀 추출
async function exportExcel(req, res) {
  try {
    const { company_id, schedule_id, date_from, date_to } = req.query;

    if (!date_from || !date_to) {
      return res.status(400).json({ success: false, error: '기간(date_from, date_to)은 필수입니다' });
    }

    const from = new Date(date_from);
    const to = new Date(date_to);
    const diffMs = to - from;
    if (diffMs < 0) {
      return res.status(400).json({ success: false, error: '시작일이 종료일보다 늦을 수 없습니다' });
    }
    if (diffMs > 92 * 24 * 60 * 60 * 1000) {
      return res.status(400).json({ success: false, error: '조회 기간은 최대 3개월입니다' });
    }

    const rows = await workReportModel.exportData({
      company_id: company_id ? parseInt(company_id) : undefined,
      schedule_id: schedule_id ? parseInt(schedule_id) : undefined,
      date_from,
      date_to
    });

    const workbook = new ExcelJS.Workbook();
    const sheet = workbook.addWorksheet('업무현황');

    sheet.columns = [
      { header: '보고일', key: 'report_date', width: 12 },
      { header: '순번', key: 'report_seq', width: 6 },
      { header: '업체', key: 'company_name', width: 18 },
      { header: '작업장', key: 'workplace_name', width: 15 },
      { header: '작업내용', key: 'schedule_description', width: 20 },
      { header: '보고내용', key: 'work_content', width: 30 },
      { header: '진행률(%)', key: 'progress_rate', width: 10 },
      { header: '작업자', key: 'worker_name', width: 12 },
      { header: '투입시간', key: 'hours_worked', width: 10 },
      { header: '이슈사항', key: 'issues', width: 25 },
      { header: '향후계획', key: 'next_plan', width: 25 },
      { header: '보고자', key: 'reporter_name', width: 10 },
      { header: '확인상태', key: 'confirm_status', width: 8 },
      { header: '확인자', key: 'confirmed_by_name', width: 10 },
    ];

    // 헤더 스타일
    sheet.getRow(1).eachCell(cell => {
      cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF059669' } };
      cell.font = { color: { argb: 'FFFFFFFF' }, bold: true };
      cell.alignment = { horizontal: 'center', vertical: 'middle' };
    });

    rows.forEach(r => {
      sheet.addRow({
        report_date: r.report_date ? String(r.report_date).substring(0, 10) : '',
        report_seq: r.report_seq,
        company_name: r.company_name || '',
        workplace_name: r.workplace_name || '',
        schedule_description: r.schedule_description || '',
        work_content: r.work_content || '',
        progress_rate: r.progress_rate || 0,
        worker_name: r.worker_name || '',
        hours_worked: r.hours_worked != null ? Number(r.hours_worked) : '',
        issues: r.issues || '',
        next_plan: r.next_plan || '',
        reporter_name: r.reporter_name || '',
        confirm_status: r.confirm_status || '',
        confirmed_by_name: r.confirmed_by_name || '',
      });
    });

    const filename = `업무현황_${date_from}_${date_to}.xlsx`;
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`);
    await workbook.xlsx.write(res);
    res.end();
  } catch (err) {
    console.error('WorkReport exportExcel error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업보고 삭제
async function deleteReport(req, res) {
  try {
    const existing = await workReportModel.findById(req.params.id);
    if (!existing) {
      return res.status(404).json({ success: false, error: '작업보고를 찾을 수 없습니다' });
    }
    const checkinId = existing.checkin_id;
    await workReportModel.deleteReport(req.params.id);

    // 남은 보고가 0건이면 체크아웃 되돌리기
    if (checkinId) {
      const remaining = await workReportModel.countByCheckin(checkinId);
      if (remaining === 0) {
        await checkinModel.resetCheckout(checkinId);
      }
    }

    res.json({ success: true, message: '삭제되었습니다' });
  } catch (err) {
    console.error('WorkReport delete error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 확인 취소
async function unconfirm(req, res) {
  try {
    const existing = await workReportModel.findById(req.params.id);
    if (!existing) {
      return res.status(404).json({ success: false, error: '작업보고를 찾을 수 없습니다' });
    }
    if (!existing.confirmed_by) {
      return res.status(400).json({ success: false, error: '이미 미확인 상태입니다' });
    }
    const row = await workReportModel.unconfirm(req.params.id);
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('WorkReport unconfirm error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

module.exports = { list, getById, myReports, create, update, confirm, reject, deleteReport, unconfirm, summary, exportExcel };
