import {
  ShopProductModel,
  shopProductValidationSchema,
} from "../models/shop_product";
import { Request, Response } from "express";

/// Create new shop product
export const createShopProduct = async (req: Request, res: Response) => {
  const { error } = shopProductValidationSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });

  try {
    // Check if user has access to this shop
    const userRole = (req as any).user?.role;
    const assignedShopIds = (req as any).user?.assignedShopIds || [];

    if (userRole === "Shopkeeper" && !assignedShopIds.includes(req.body.shopId)) {
      return res.status(403).json({ error: "Access denied. You can only create products for shops assigned to you." });
    }

    const newShopProduct = await ShopProductModel.create(req.body);
    return res
      .status(200)
      .json({
        message: "Shop product created successfully.",
        id: newShopProduct.id,
      });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Get all shop products (filtered by user role)
export const getAllShopProducts = async (req: Request, res: Response) => {
  try {
    const userRole = (req as any).user?.role;
    const assignedShopIds = (req as any).user?.assignedShopIds || [];

    let shopProducts;

    if (userRole === "Shopkeeper") {
      if (assignedShopIds.length === 0) {
        return res.status(200).json([]); // Return empty array if no shops assigned
      }
      
      // Get only products from shops assigned to this shopkeeper
      shopProducts = await ShopProductModel.findAll({
        where: { 
          isDeleted: false,
          shopId: assignedShopIds
        },
      });
    } else {
      // Admin can see all shop products
      shopProducts = await ShopProductModel.findAll({
        where: { isDeleted: false },
      });
    }

    return res.status(200).json(shopProducts);
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Get shop products for a specific shop
export const getShopProductsByShop = async (req: Request, res: Response) => {
  try {
    const shopId = parseInt(req.params.shopId);
    const userRole = (req as any).user?.role;
    const assignedShopIds = (req as any).user?.assignedShopIds || [];

    // Check if user has access to this shop
    if (userRole === "Shopkeeper" && !assignedShopIds.includes(shopId)) {
      return res.status(403).json({ error: "Access denied. You can only view products for shops assigned to you." });
    }

    const shopProducts = await ShopProductModel.findAll({
      where: { 
        shopId: shopId,
        isDeleted: false 
      },
    });

    return res.status(200).json(shopProducts);
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Update existing shop product
export const updateShopProduct = async (req: Request, res: Response) => {
  try {
    // Find the shop product by ID
    const shopProduct = await ShopProductModel.findByPk(req.params.id);
    if (!shopProduct)
      return res.status(404).json({ error: "Shop product not found." });

    // Check if user has access to this shop
    const userRole = (req as any).user?.role;
    const assignedShopIds = (req as any).user?.assignedShopIds || [];

    if (userRole === "Shopkeeper" && !assignedShopIds.includes(shopProduct.shopId)) {
      return res.status(403).json({ error: "Access denied. You can only update products for shops assigned to you." });
    }

    // Validate the request body
    const { error } = shopProductValidationSchema.validate(req.body);
    if (error) return res.status(400).json({ error: error.details[0].message });

    // Update the shop product details
    await shopProduct.update(req.body);

    // Send success response
    return res
      .status(200)
      .json({
        message: "Shop product updated successfully.",
        id: shopProduct.id,
      });
  } catch (ex) {
    console.error(`Error updating shop product: ${ex}`);
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Delete a shop product
export const deleteShopProduct = async (req: Request, res: Response) => {
  try {
    // Find the shop product by ID
    const shopProduct = await ShopProductModel.findByPk(req.params.id);
    if (!shopProduct)
      return res.status(404).json({ error: "Shop product not found." });

    // Check if user has access to this shop
    const userRole = (req as any).user?.role;
    const assignedShopIds = (req as any).user?.assignedShopIds || [];

    if (userRole === "Shopkeeper" && !assignedShopIds.includes(shopProduct.shopId)) {
      return res.status(403).json({ error: "Access denied. You can only delete products for shops assigned to you." });
    }

    // Soft delete the shop product
    await shopProduct.update({ isDeleted: true });

    // Send success response
    return res
      .status(200)
      .json({ message: "Shop product deleted successfully." });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};