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

// 업체 목록
async function list(req, res) {
  try {
    const { search, is_active } = req.query;
    const rows = await partnerModel.findAll({
      search,
      is_active: is_active !== undefined ? is_active === 'true' || is_active === '1' : undefined
    });
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Partner list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 업체 상세 (작업자 포함)
async function getById(req, res) {
  try {
    const company = await partnerModel.findById(req.params.id);
    if (!company) return res.status(404).json({ success: false, error: '업체를 찾을 수 없습니다' });
    const workers = await partnerModel.findWorkersByCompany(req.params.id);
    res.json({ success: true, data: { ...company, workers } });
  } catch (err) {
    console.error('Partner get error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 업체 등록
async function create(req, res) {
  try {
    const { company_name } = req.body;
    if (!company_name || !company_name.trim()) {
      return res.status(400).json({ success: false, error: '업체명은 필수입니다' });
    }
    const company = await partnerModel.create(req.body);
    res.status(201).json({ success: true, data: company });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ success: false, error: '이미 등록된 사업자번호입니다' });
    }
    console.error('Partner create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 업체 수정
async function update(req, res) {
  try {
    const company = await partnerModel.update(req.params.id, req.body);
    if (!company) return res.status(404).json({ success: false, error: '업체를 찾을 수 없습니다' });
    res.json({ success: true, data: company });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ success: false, error: '이미 등록된 사업자번호입니다' });
    }
    console.error('Partner update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 업체 비활성화
async function deactivate(req, res) {
  try {
    await partnerModel.deactivate(req.params.id);
    res.json({ success: true, message: '비활성화 완료' });
  } catch (err) {
    console.error('Partner deactivate error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 업체 자동완성 검색
async function searchCompanies(req, res) {
  try {
    const q = req.query.q || '';
    if (q.length < 1) return res.json({ success: true, data: [] });
    const rows = await partnerModel.search(q);
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Partner search error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 소속 작업자 목록
async function listWorkers(req, res) {
  try {
    const rows = await partnerModel.findWorkersByCompany(req.params.id);
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Workers list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업자 등록
async function createWorker(req, res) {
  try {
    const { worker_name, is_team_leader, phone } = req.body;
    if (!worker_name || !worker_name.trim()) {
      return res.status(400).json({ success: false, error: '작업자명은 필수입니다' });
    }
    if (is_team_leader && (!phone || !phone.trim())) {
      return res.status(400).json({ success: false, error: '팀장급은 연락처 필수입니다' });
    }
    const worker = await partnerModel.createWorker(req.params.id, req.body);
    res.status(201).json({ success: true, data: worker });
  } catch (err) {
    console.error('Worker create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업자 수정
async function updateWorker(req, res) {
  try {
    const { is_team_leader, phone } = req.body;
    if (is_team_leader && (!phone || !phone.trim())) {
      return res.status(400).json({ success: false, error: '팀장급은 연락처 필수입니다' });
    }
    const worker = await partnerModel.updateWorker(req.params.id, req.body);
    if (!worker) return res.status(404).json({ success: false, error: '작업자를 찾을 수 없습니다' });
    res.json({ success: true, data: worker });
  } catch (err) {
    console.error('Worker update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

// 작업자 비활성화
async function deactivateWorker(req, res) {
  try {
    await partnerModel.deactivateWorker(req.params.id);
    res.json({ success: true, message: '비활성화 완료' });
  } catch (err) {
    console.error('Worker deactivate error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

module.exports = {
  list, getById, create, update, deactivate, searchCompanies,
  listWorkers, createWorker, updateWorker, deactivateWorker
};
