const storeModel = require("../models/store.model");
const { sendError } = require("../utils/http");
const { logError } = require("../utils/logger");

// Get all available stores
exports.getAllStores = async (req, res) => {
  try {
    const stores = await storeModel.getAllStores();
    res.json(stores);
  } catch (error) {
    logError(req, "stores.getAllStores", error);
    sendError(res, 500, "Failed to fetch stores");
  }
};

// Get stores for household
exports.getHouseholdStores = async (req, res) => {
  try {
    const stores = await storeModel.getHouseholdStores(req.params.householdId);
    res.json(stores);
  } catch (error) {
    logError(req, "stores.getHouseholdStores", error);
    sendError(res, 500, "Failed to fetch household stores");
  }
};

// Add store to household
exports.addStoreToHousehold = async (req, res) => {
  try {
    const { storeId, isDefault } = req.body;
    // console.log("Adding store to household:", { householdId: req.params.householdId, storeId, isDefault });
    if (!storeId) {
      return sendError(res, 400, "Store ID is required");
    }

    const store = await storeModel.getStoreById(storeId);
    if (!store) return sendError(res, 404, "Store not found");
    const foundStores = await storeModel.getHouseholdStores(req.params.householdId);
    // if (foundStores.length == 0) isDefault = 'true';

    await storeModel.addStoreToHousehold(
      req.params.householdId,
      storeId,
      foundStores.length == 0 ? true : isDefault || false
    );

    res.status(201).json({
      message: "Store added to household successfully",
      store
    });
  } catch (error) {
    logError(req, "stores.addStoreToHousehold", error);
    sendError(res, 500, "Failed to add store to household");
  }
};

// Remove store from household
exports.removeStoreFromHousehold = async (req, res) => {
  try {
    await storeModel.removeStoreFromHousehold(
      req.params.householdId,
      req.params.storeId
    );

    res.json({ message: "Store removed from household successfully" });
  } catch (error) {
    logError(req, "stores.removeStoreFromHousehold", error);
    sendError(res, 500, "Failed to remove store from household");
  }
};

// Set default store
exports.setDefaultStore = async (req, res) => {
  try {
    await storeModel.setDefaultStore(
      req.params.householdId,
      req.params.storeId
    );

    res.json({ message: "Default store updated successfully" });
  } catch (error) {
    logError(req, "stores.setDefaultStore", error);
    sendError(res, 500, "Failed to set default store");
  }
};

// Create store (system admin only)
exports.createStore = async (req, res) => {
  try {
    const { name, default_zones } = req.body;

    if (!name || name.trim().length === 0) {
      return sendError(res, 400, "Store name is required");
    }

    const store = await storeModel.createStore(name.trim(), default_zones || null);

    res.status(201).json({
      message: "Store created successfully",
      store
    });
  } catch (error) {
    logError(req, "stores.createStore", error);
    if (error.code === '23505') { // Unique violation
      return sendError(res, 400, "Store with this name already exists");
    }
    sendError(res, 500, "Failed to create store");
  }
};

// Update store (system admin only)
exports.updateStore = async (req, res) => {
  try {
    const { name, default_zones } = req.body;

    const store = await storeModel.updateStore(req.params.storeId, {
      name: name?.trim(),
      default_zones
    });

    if (!store) {
      return sendError(res, 404, "Store not found");
    }

    res.json({
      message: "Store updated successfully",
      store
    });
  } catch (error) {
    logError(req, "stores.updateStore", error);
    sendError(res, 500, "Failed to update store");
  }
};

// Delete store (system admin only)
exports.deleteStore = async (req, res) => {
  try {
    await storeModel.deleteStore(req.params.storeId);
    res.json({ message: "Store deleted successfully" });
  } catch (error) {
    logError(req, "stores.deleteStore", error);
    if (error.message.includes('in use')) {
      return sendError(res, 400, error.message);
    }
    sendError(res, 500, "Failed to delete store");
  }
};
