import { Order, OrderValidationSchema } from "../models/order";
import { UserModel } from "../models/user";
import { Request, Response } from "express";

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

  try {
    // Verify that the masterId exists and has Master role
    const master = await UserModel.findOne({
      where: { 
        id: req.body.masterId, 
        role: "Master",
        isDeleted: false 
      }
    });

    if (!master) {
      return res.status(400).json({ error: "Invalid Master ID. User must exist and have Master role." });
    }

    // Create order with default status "Pending"
    const orderData = {
      ...req.body,
      status: "Pending" // Always set to Pending when creating new order
    };

    const order = await Order.create(orderData);
    return res
      .status(200)
      .json({ 
        message: "Order created successfully and assigned to Master", 
        id: order.id,
        masterId: order.masterId,
        status: order.status
      });
  } catch (err) {
    return res.status(500).json({ error: `Internal server error: ${err}` });
  }
};

/// Get all orders (filtered by user role)
export const getAllOrder = async (req: Request, res: Response) => {
  try {
    const userRole = (req as any).user?.role;
    const userId = (req as any).user?.id;

    let orders;

    if (userRole === "Master") {
      // Masters can only see orders assigned to them
      orders = await Order.findAll({
        where: { 
          masterId: userId,
          isDeleted: false 
        },
      });
    } else {
      // Admin, Shopkeeper, Tailor can see all orders
      orders = await Order.findAll({
        where: { isDeleted: false },
      });
    }

    return res.status(200).json(orders);
  } catch (err) {
    console.log(`Here is error: ${err}`)
    return res.status(500).json({ Error: `Internal server error: ${err}` });
  }
};

/// Get orders assigned to current Master
export const getMyOrders = async (req: Request, res: Response) => {
  try {
    const userRole = (req as any).user?.role;
    const userId = (req as any).user?.id;

    if (userRole !== "Master") {
      return res.status(403).json({ error: "Access denied. Only Masters can access this endpoint." });
    }

    const orders = await Order.findAll({
      where: { 
        masterId: userId,
        isDeleted: false 
      },
    });

    return res.status(200).json(orders);
  } catch (err) {
    return res.status(500).json({ error: `Internal server error: ${err}` });
  }
};

/// Get all Masters for order assignment
export const getMasters = async (req: Request, res: Response) => {
  try {
    const masters = await UserModel.findAll({
      where: { 
        role: "Master",
        isDeleted: false 
      },
      attributes: ['id', 'name', 'email', 'phoneNumber']
    });
    return res.status(200).json(masters);
  } catch (err) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Update order (including status updates)
export const updateOrder = async (req: Request, res: Response) => {
  const { error } = OrderValidationSchema.validate(req.body);
  if (error) return res.status(400).json({ Error: error.details[0].message });

  try {
    const order = await Order.findByPk(req.params.id);
    if (!order || order.isDeleted) {
      return res.status(404).json({ Error: "Order not found" });
    }

    // Check if user has permission to update this order
    const userRole = (req as any).user?.role;
    const userId = (req as any).user?.id;

    if (userRole === "Master" && order.masterId !== userId) {
      return res.status(403).json({ error: "Access denied. You can only update orders assigned to you." });
    }

    // If masterId is being updated, verify the new master exists and has Master role
    if (req.body.masterId && req.body.masterId !== order.masterId) {
      const master = await UserModel.findOne({
        where: { 
          id: req.body.masterId, 
          role: "Master",
          isDeleted: false 
        }
      });

      if (!master) {
        return res.status(400).json({ error: "Invalid Master ID. User must exist and have Master role." });
      }
    }

    const orderUpdated = await order.update(req.body);
    return res.status(200).json({ 
      message: "Order updated successfully",
      order: orderUpdated 
    });
  } catch (err) {
    return res.status(500).json({ Error: `Internal server error: ${err}` });
  }
};

/// Update order status (for Masters to update their order progress)
export const updateOrderStatus = async (req: Request, res: Response) => {
  try {
    const { status } = req.body;
    const validStatuses = ["Pending", "Tailor", "Stitching", "Kajbutton", "Done"];
    
    if (!status || !validStatuses.includes(status)) {
      return res.status(400).json({ 
        error: "Invalid status. Valid statuses are: " + validStatuses.join(", ") 
      });
    }

    const order = await Order.findByPk(req.params.id);
    if (!order || order.isDeleted) {
      return res.status(404).json({ error: "Order not found" });
    }

    // Check if user has permission to update this order status
    const userRole = (req as any).user?.role;
    const userId = (req as any).user?.id;

    if (userRole === "Master" && order.masterId !== userId) {
      return res.status(403).json({ error: "Access denied. You can only update status of orders assigned to you." });
    }

    await order.update({ status });
    return res.status(200).json({ 
      message: "Order status updated successfully",
      orderId: order.id,
      newStatus: status
    });
  } catch (err) {
    return res.status(500).json({ error: `Internal server error: ${err}` });
  }
};

/// Delete order
export const deleteOrder = async (req: Request, res: Response) => {
  try {
    const order = await Order.findByPk(req.params.id);
    if (!order || order.isDeleted) {
      return res.status(404).json({ Error: "Order not found" });
    }

    // Check if user has permission to delete this order
    const userRole = (req as any).user?.role;
    const userId = (req as any).user?.id;

    if (userRole === "Master" && order.masterId !== userId) {
      return res.status(403).json({ error: "Access denied. You can only delete orders assigned to you." });
    }

    await order.update({ isDeleted: true });
    return res.status(200).json({ message: "Order deleted successfully." });
  } catch (err) {
    return res.status(500).json({ Error: `Internal server error: ${err}` });
  }
};
