// ============================================
// STORE CONTROLLER
// controllers/storeController.js
// ============================================


const { Store, Register,User } = require('../models');
const { Op } = require('sequelize');

// Get all stores with pagination and search
exports.getAllStores = async (req, res) => {
  try {
    const { page = 1, limit = 20, search = '' } = req.query;
    const offset = (parseInt(page) - 1) * parseInt(limit);

    const whereClause = search
      ? {
          [Op.or]: [
            { name: { [Op.like]: `%${search}%` } },
            { code: { [Op.like]: `%${search}%` } },
            { city: { [Op.like]: `%${search}%` } }
          ]
        }
      : {};

    const { count, rows: stores } = await Store.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: offset,
      include: [
        {
          model: Register,
          as: 'registers',
          attributes: ['id', 'name', 'status', 'currentCash']
        },
        {
          model: User,
          as: 'users',
          attributes: ['id', 'lastName', 'email']
        }
      ],
      order: [['createdAt', 'DESC']]
    });


    const storeData = stores.map(store => store.toJSON());

    console.log(`FETCHED ${storeData} STORES out of ${count} total matching stores.`);

    res.json({
      success: true,
      mystores: storeData,
      stores,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / parseInt(limit)),
      totalStores: count
    });
  } catch (error) {
    console.error('Error fetching stores:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch stores',
      error: error.message
    });
  }
};

// Get single store by ID
exports.getStoreById = async (req, res) => {
  try {
    const { id } = req.params;

    const store = await Store.findByPk(id, {
      include: [
        {
          model: Register,
          as: 'registers',
          attributes: ['id', 'name', 'status', 'currentCash', 'openingCash']
        },
        {
          model: User,
          as: 'users',
          attributes: ['id', 'name', 'email', 'role']
        }
      ]
    });

    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    res.json({
      success: true,
      store
    });
  } catch (error) {
    console.error('Error fetching store:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch store',
      error: error.message
    });
  }
};

// Create new store
exports.createStore = async (req, res) => {
  try {
    const {
      name,
      code,
      address,
      city,
      state,
      country,
      postalCode,
      phone,
      email,
      taxId
    } = req.body;

    // Validation
    if (!name || !code || !city || !phone) {
      return res.status(400).json({
        success: false,
        message: 'Name, code, city, and phone are required'
      });
    }

    // Check if code already exists
    const existingStore = await Store.findOne({ where: { code: code.toUpperCase() } });
    if (existingStore) {
      return res.status(409).json({
        success: false,
        message: 'Store code already exists'
      });
    }

    const store = await Store.create({
      name,
      code: code.toUpperCase(),
      address,
      city,
      state,
      country: country || 'Kenya',
      postalCode,
      phone,
      email,
      taxId,
      isActive: true,
      createdBy: req.user?.id // Assuming auth middleware adds user to request
    });

    res.status(201).json({
      success: true,
      message: 'Store created successfully',
      store
    });
  } catch (error) {
    console.error('Error creating store:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to create store',
      error: error.message
    });
  }
};

// Update store
exports.updateStore = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name,
      code,
      address,
      city,
      state,
      country,
      postalCode,
      phone,
      email,
      taxId
    } = req.body;

    const store = await Store.findByPk(id);

    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    // Check if code is being changed and if it already exists
    if (code && code.toUpperCase() !== store.code) {
      const existingStore = await Store.findOne({
        where: { code: code.toUpperCase(), id: { [Op.ne]: id } }
      });
      if (existingStore) {
        return res.status(409).json({
          success: false,
          message: 'Store code already exists'
        });
      }
    }

    await store.update({
      name: name || store.name,
      code: code ? code.toUpperCase() : store.code,
      address: address !== undefined ? address : store.address,
      city: city || store.city,
      state: state !== undefined ? state : store.state,
      country: country || store.country,
      postalCode: postalCode !== undefined ? postalCode : store.postalCode,
      phone: phone || store.phone,
      email: email !== undefined ? email : store.email,
      taxId: taxId !== undefined ? taxId : store.taxId,
      updatedBy: req.user?.id
    });

    res.json({
      success: true,
      message: 'Store updated successfully',
      store
    });
  } catch (error) {
    console.error('Error updating store:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update store',
      error: error.message
    });
  }
};

// Deactivate store
exports.deactivateStore = async (req, res) => {
  try {
    const { id } = req.params;

    const store = await Store.findByPk(id, {
      include: [{ model: Register, as: 'registers' }]
    });

    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    // Check if there are open registers
    const openRegisters = store.registers?.filter(r => r.status === 'open');
    if (openRegisters && openRegisters.length > 0) {
      return res.status(400).json({
        success: false,
        message: 'Cannot deactivate store with open registers. Please close all registers first.'
      });
    }

    await store.update({
      isActive: false,
      deactivatedBy: req.user?.id,
      deactivatedAt: new Date()
    });

    res.json({
      success: true,
      message: 'Store deactivated successfully',
      store
    });
  } catch (error) {
    console.error('Error deactivating store:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to deactivate store',
      error: error.message
    });
  }
};

// Activate store
exports.activateStore = async (req, res) => {
  try {
    const { id } = req.params;

    const store = await Store.findByPk(id);

    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    await store.update({
      isActive: true,
      activatedBy: req.user?.id,
      activatedAt: new Date()
    });

    res.json({
      success: true,
      message: 'Store activated successfully',
      store
    });
  } catch (error) {
    console.error('Error activating store:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to activate store',
      error: error.message
    });
  }
};

// Delete store (soft delete)
exports.deleteStore = async (req, res) => {
  try {
    const { id } = req.params;

    const store = await Store.findByPk(id, {
      include: [{ model: Register, as: 'registers' }]
    });

    if (!store) {
      return res.status(404).json({
        success: false,
        message: 'Store not found'
      });
    }

    // Check if there are any registers
    if (store.registers && store.registers.length > 0) {
      return res.status(400).json({
        success: false,
        message: 'Cannot delete store with existing registers. Please delete all registers first.'
      });
    }

    // Soft delete (if using paranoid)
    await store.destroy();

    res.json({
      success: true,
      message: 'Store deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting store:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to delete store',
      error: error.message
    });
  }
};