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

// 일정 목록
async function list(req, res) {
  try {
    const { company, company_id, date_from, date_to, status, project_id, page, limit } = req.query;
    const { rows, total } = await scheduleModel.findAll({
      company: company || undefined,
      company_id: company_id ? parseInt(company_id) : undefined,
      date_from,
      date_to,
      status,
      project_id: project_id ? parseInt(project_id) : undefined,
      page: page ? parseInt(page) : 1,
      limit: limit ? parseInt(limit) : 50
    });
    res.json({ success: true, data: rows, total });
  } catch (err) {
    console.error('Schedule list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

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

// 내 일정 (협력업체 포탈)
async function mySchedules(req, res) {
  try {
    const companyId = req.user.partner_company_id;
    if (!companyId) {
      return res.status(403).json({ success: false, error: '협력업체 계정이 아닙니다' });
    }
    const [schedules, requests] = await Promise.all([
      scheduleModel.findActiveByCompany(companyId),
      scheduleModel.findRequestsByCompany(companyId)
    ]);
    res.json({ success: true, data: { schedules, requests } });
  } catch (err) {
    console.error('Schedule mySchedules error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 협력업체 작업 신청
async function requestSchedule(req, res) {
  try {
    const companyId = req.user.partner_company_id;
    if (!companyId) {
      return res.status(403).json({ success: false, error: '협력업체 계정이 아닙니다' });
    }
    const { start_date, work_description, workplace_name, expected_workers } = req.body;
    if (!start_date) {
      return res.status(400).json({ success: false, error: '작업일은 필수입니다' });
    }
    const data = {
      company_id: companyId,
      project_id: null,
      start_date,
      end_date: start_date,
      work_description: work_description || null,
      workplace_name: workplace_name || null,
      expected_workers: expected_workers || null,
      requested_by: req.user.user_id || req.user.id,
      status: 'requested'
    };
    const row = await scheduleModel.create(data);
    res.status(201).json({ success: true, data: row });
  } catch (err) {
    console.error('Schedule requestSchedule error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 구매팀 승인
async function approveRequest(req, res) {
  try {
    const schedule = await scheduleModel.findById(req.params.id);
    if (!schedule) return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
    if (schedule.status !== 'requested') {
      return res.status(400).json({ success: false, error: '신청 상태가 아닙니다' });
    }
    const updateData = {
      status: 'scheduled',
      registered_by: req.user.user_id || req.user.id
    };
    if (req.body.project_id !== undefined) updateData.project_id = req.body.project_id;
    if (req.body.workplace_name !== undefined) updateData.workplace_name = req.body.workplace_name;
    if (req.body.start_date) updateData.start_date = req.body.start_date;
    if (req.body.end_date) updateData.end_date = req.body.end_date;
    if (req.body.expected_workers !== undefined) updateData.expected_workers = req.body.expected_workers;
    if (req.body.work_description !== undefined) updateData.work_description = req.body.work_description;

    // update() handles dynamic fields including status and registered_by via the fields map
    // But registered_by is not in the update() fields list, so use raw query for it
    const db = require('../models/partnerModel').getPool();
    const fields = ['status = ?', 'registered_by = ?'];
    const values = ['scheduled', updateData.registered_by];
    if (updateData.project_id !== undefined) { fields.push('project_id = ?'); values.push(updateData.project_id || null); }
    if (updateData.workplace_name !== undefined) { fields.push('workplace_name = ?'); values.push(updateData.workplace_name || null); }
    if (updateData.start_date) { fields.push('start_date = ?'); values.push(updateData.start_date); }
    if (updateData.end_date) { fields.push('end_date = ?'); values.push(updateData.end_date); }
    if (updateData.expected_workers !== undefined) { fields.push('expected_workers = ?'); values.push(updateData.expected_workers || null); }
    if (updateData.work_description !== undefined) { fields.push('work_description = ?'); values.push(updateData.work_description || null); }
    values.push(req.params.id);
    await db.query(`UPDATE partner_schedules SET ${fields.join(', ')} WHERE id = ?`, values);

    const row = await scheduleModel.findById(req.params.id);
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Schedule approveRequest error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 구매팀 반려
async function rejectRequest(req, res) {
  try {
    const schedule = await scheduleModel.findById(req.params.id);
    if (!schedule) return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
    if (schedule.status !== 'requested') {
      return res.status(400).json({ success: false, error: '신청 상태가 아닙니다' });
    }
    const row = await scheduleModel.updateStatus(req.params.id, 'rejected');
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Schedule rejectRequest error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 일정 등록
async function create(req, res) {
  try {
    const { company_id, start_date, end_date } = req.body;
    if (!company_id) {
      return res.status(400).json({ success: false, error: '업체를 선택해주세요' });
    }
    if (!start_date) {
      return res.status(400).json({ success: false, error: '시작일은 필수입니다' });
    }
    if (!end_date) {
      return res.status(400).json({ success: false, error: '종료일은 필수입니다' });
    }
    if (end_date < start_date) {
      return res.status(400).json({ success: false, error: '종료일은 시작일 이후여야 합니다' });
    }
    const data = {
      ...req.body,
      registered_by: req.user.user_id || req.user.id
    };
    const row = await scheduleModel.create(data);
    res.status(201).json({ success: true, data: row });
  } catch (err) {
    console.error('Schedule create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 일정 수정
async function update(req, res) {
  try {
    const { start_date, end_date } = req.body;
    if (start_date && end_date && end_date < start_date) {
      return res.status(400).json({ success: false, error: '종료일은 시작일 이후여야 합니다' });
    }
    const row = await scheduleModel.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('Schedule update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 일정 상태 변경
async function updateStatus(req, res) {
  try {
    const { status } = req.body;
    if (!status) {
      return res.status(400).json({ success: false, error: '상태값은 필수입니다' });
    }
    const row = await scheduleModel.updateStatus(req.params.id, status);
    if (!row) return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
    res.json({ success: true, data: row });
  } catch (err) {
    console.error('Schedule updateStatus error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 일정 삭제 (admin 전용, 관련 데이터 캐스케이드 삭제)
async function deleteSchedule(req, res) {
  try {
    const result = await scheduleModel.deleteSchedule(req.params.id);
    if (result === null) {
      return res.status(404).json({ success: false, error: '일정을 찾을 수 없습니다' });
    }
    res.json({ success: true, message: '삭제 완료' });
  } catch (err) {
    console.error('Schedule delete error:', err);
    res.status(500).json({ success: false, error: '일정 삭제 중 오류가 발생했습니다' });
  }
}

module.exports = { list, getById, mySchedules, create, update, updateStatus, deleteSchedule, requestSchedule, approveRequest, rejectRequest };
