/**
 * Workplace Model
 *
 * workplaces + workplace_categories 테이블 CRUD (MariaDB)
 */

const { getPool } = require('./userModel');

async function getAll() {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT w.*, c.category_name
     FROM workplaces w
     LEFT JOIN workplace_categories c ON w.category_id = c.category_id
     ORDER BY w.display_priority ASC, w.workplace_id DESC`
  );
  return rows;
}

async function getById(id) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT w.*, c.category_name
     FROM workplaces w
     LEFT JOIN workplace_categories c ON w.category_id = c.category_id
     WHERE w.workplace_id = ?`,
    [id]
  );
  return rows[0] || null;
}

async function getCategories() {
  const db = getPool();
  const [rows] = await db.query(
    'SELECT * FROM workplace_categories WHERE is_active = TRUE ORDER BY display_order ASC'
  );
  return rows;
}

async function create({ workplace_name, category_id, workplace_purpose, description, display_priority }) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO workplaces (workplace_name, category_id, workplace_purpose, description, display_priority)
     VALUES (?, ?, ?, ?, ?)`,
    [workplace_name, category_id || null, workplace_purpose || null, description || null, display_priority || 0]
  );
  return getById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];

  if (data.workplace_name !== undefined) { fields.push('workplace_name = ?'); values.push(data.workplace_name); }
  if (data.category_id !== undefined) { fields.push('category_id = ?'); values.push(data.category_id || null); }
  if (data.workplace_purpose !== undefined) { fields.push('workplace_purpose = ?'); values.push(data.workplace_purpose); }
  if (data.description !== undefined) { fields.push('description = ?'); values.push(data.description || null); }
  if (data.is_active !== undefined) { fields.push('is_active = ?'); values.push(data.is_active); }
  if (data.display_priority !== undefined) { fields.push('display_priority = ?'); values.push(data.display_priority); }

  if (fields.length === 0) return getById(id);

  values.push(id);
  await db.query(
    `UPDATE workplaces SET ${fields.join(', ')} WHERE workplace_id = ?`,
    values
  );
  return getById(id);
}

async function deactivate(id) {
  const db = getPool();
  await db.query(
    'UPDATE workplaces SET is_active = FALSE WHERE workplace_id = ?',
    [id]
  );
}

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

async function updateCategoryLayoutImage(id, imagePath) {
  const db = getPool();
  await db.query(
    'UPDATE workplace_categories SET layout_image = ? WHERE category_id = ?',
    [imagePath, id]
  );
  const [rows] = await db.query('SELECT * FROM workplace_categories WHERE category_id = ?', [id]);
  return rows[0] || null;
}

async function createMapRegion({ workplace_id, category_id, x_start, y_start, x_end, y_end, shape, polygon_points }) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO workplace_map_regions (workplace_id, category_id, x_start, y_start, x_end, y_end, shape, polygon_points)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
    [workplace_id, category_id, x_start, y_start, x_end, y_end, shape || 'rect', polygon_points || null]
  );
  const [rows] = await db.query('SELECT * FROM workplace_map_regions WHERE region_id = ?', [result.insertId]);
  return rows[0];
}

async function getMapRegionsByCategory(categoryId) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT r.*, w.workplace_name
     FROM workplace_map_regions r
     LEFT JOIN workplaces w ON r.workplace_id = w.workplace_id
     WHERE r.category_id = ?
     ORDER BY r.region_id ASC`,
    [categoryId]
  );
  return rows;
}

async function updateMapRegion(regionId, { x_start, y_start, x_end, y_end, workplace_id, shape, polygon_points }) {
  const db = getPool();
  const fields = [];
  const values = [];

  if (x_start !== undefined) { fields.push('x_start = ?'); values.push(x_start); }
  if (y_start !== undefined) { fields.push('y_start = ?'); values.push(y_start); }
  if (x_end !== undefined) { fields.push('x_end = ?'); values.push(x_end); }
  if (y_end !== undefined) { fields.push('y_end = ?'); values.push(y_end); }
  if (workplace_id !== undefined) { fields.push('workplace_id = ?'); values.push(workplace_id); }
  if (shape !== undefined) { fields.push('shape = ?'); values.push(shape); }
  if (polygon_points !== undefined) { fields.push('polygon_points = ?'); values.push(polygon_points); }

  if (fields.length === 0) return null;

  values.push(regionId);
  await db.query(`UPDATE workplace_map_regions SET ${fields.join(', ')} WHERE region_id = ?`, values);
  const [rows] = await db.query(
    `SELECT r.*, w.workplace_name
     FROM workplace_map_regions r
     LEFT JOIN workplaces w ON r.workplace_id = w.workplace_id
     WHERE r.region_id = ?`,
    [regionId]
  );
  return rows[0] || null;
}

async function deleteMapRegion(regionId) {
  const db = getPool();
  await db.query('DELETE FROM workplace_map_regions WHERE region_id = ?', [regionId]);
}

async function updateWorkplaceLayoutImage(id, imagePath) {
  const db = getPool();
  await db.query('UPDATE workplaces SET layout_image = ? WHERE workplace_id = ?', [imagePath, id]);
  return getById(id);
}

module.exports = {
  getAll, getById, getCategories, create, update, deactivate,
  updateCategoryLayoutImage, createMapRegion, getMapRegionsByCategory, updateMapRegion, deleteMapRegion,
  updateWorkplaceLayoutImage
};
