/**
 * Workplace Controller
 *
 * 작업장 CRUD + 카테고리 조회
 */

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

async function getAll(req, res, next) {
  try {
    const workplaces = await workplaceModel.getAll();
    res.json({ success: true, data: workplaces });
  } catch (err) {
    next(err);
  }
}

async function getById(req, res, next) {
  try {
    const wp = await workplaceModel.getById(parseInt(req.params.id));
    if (!wp) {
      return res.status(404).json({ success: false, error: '작업장을 찾을 수 없습니다' });
    }
    res.json({ success: true, data: wp });
  } catch (err) {
    next(err);
  }
}

async function getCategories(req, res, next) {
  try {
    const categories = await workplaceModel.getCategories();
    res.json({ success: true, data: categories });
  } catch (err) {
    next(err);
  }
}

async function create(req, res, next) {
  try {
    const { workplace_name } = req.body;
    if (!workplace_name) {
      return res.status(400).json({ success: false, error: '작업장명은 필수입니다' });
    }
    const wp = await workplaceModel.create(req.body);
    res.status(201).json({ success: true, data: wp });
  } catch (err) {
    next(err);
  }
}

async function update(req, res, next) {
  try {
    const id = parseInt(req.params.id);
    const wp = await workplaceModel.update(id, req.body);
    if (!wp) {
      return res.status(404).json({ success: false, error: '작업장을 찾을 수 없습니다' });
    }
    res.json({ success: true, data: wp });
  } catch (err) {
    next(err);
  }
}

async function remove(req, res, next) {
  try {
    const id = parseInt(req.params.id);
    await workplaceModel.deactivate(id);
    res.json({ success: true, message: '작업장이 비활성화되었습니다' });
  } catch (err) {
    next(err);
  }
}

// ==================== 구역지도 ====================

async function uploadCategoryLayoutImage(req, res, next) {
  try {
    if (!req.file) {
      return res.status(400).json({ success: false, error: '이미지 파일이 필요합니다' });
    }
    const id = parseInt(req.params.id);
    const imagePath = `/uploads/${req.file.filename}`;
    const category = await workplaceModel.updateCategoryLayoutImage(id, imagePath);
    if (!category) {
      return res.status(404).json({ success: false, error: '카테고리를 찾을 수 없습니다' });
    }
    res.json({ success: true, data: { image_path: imagePath, category } });
  } catch (err) {
    next(err);
  }
}

async function createMapRegion(req, res, next) {
  try {
    const { workplace_id, category_id } = req.body;
    if (!workplace_id || !category_id) {
      return res.status(400).json({ success: false, error: 'workplace_id와 category_id는 필수입니다' });
    }
    const region = await workplaceModel.createMapRegion(req.body);
    res.status(201).json({ success: true, data: region });
  } catch (err) {
    next(err);
  }
}

async function getMapRegionsByCategory(req, res, next) {
  try {
    const categoryId = parseInt(req.params.categoryId);
    const regions = await workplaceModel.getMapRegionsByCategory(categoryId);
    res.json({ success: true, data: regions });
  } catch (err) {
    next(err);
  }
}

async function updateMapRegion(req, res, next) {
  try {
    const regionId = parseInt(req.params.id);
    const region = await workplaceModel.updateMapRegion(regionId, req.body);
    if (!region) {
      return res.status(404).json({ success: false, error: '영역을 찾을 수 없습니다' });
    }
    res.json({ success: true, data: region });
  } catch (err) {
    next(err);
  }
}

async function deleteMapRegion(req, res, next) {
  try {
    const regionId = parseInt(req.params.id);
    await workplaceModel.deleteMapRegion(regionId);
    res.json({ success: true, message: '영역이 삭제되었습니다' });
  } catch (err) {
    next(err);
  }
}

async function uploadWorkplaceLayoutImage(req, res, next) {
  try {
    if (!req.file) return res.status(400).json({ success: false, error: '이미지 파일이 필요합니다' });
    const id = parseInt(req.params.id);
    const imagePath = `/uploads/${req.file.filename}`;
    const wp = await workplaceModel.updateWorkplaceLayoutImage(id, imagePath);
    if (!wp) return res.status(404).json({ success: false, error: '작업장을 찾을 수 없습니다' });
    res.json({ success: true, data: { image_path: imagePath, workplace: wp } });
  } catch (err) { next(err); }
}

module.exports = {
  getAll, getById, getCategories, create, update, remove,
  uploadCategoryLayoutImage, uploadWorkplaceLayoutImage,
  createMapRegion, getMapRegionsByCategory, updateMapRegion, deleteMapRegion
};
