import serviceRequest from "../DB/Model/serviceRequest.js";
import { createServiceRequestSchema, updateServiceRequestSchema } from "../Utils/Validator/serviceRequest.validation.js";


export const createServiceRequest = async (req, res) => {
    try {
        const { error } = createServiceRequestSchema.validate(req.body);
        if (error) {
            return res.status(400).json({ status: false, message: error.details[0].message });
        }

        const userId = req.user._id;

        const newRequest = await serviceRequest.create({
            ...req.body,
            created_by: userId,
        });

        res.status(201).json({ status: true, message: "Service request created", data: newRequest });
    } catch (err) {
        res.status(500).json({ status: false, message: "Server error", error: err.message });
    }
};

export const getAllServiceRequests = async (req, res) => {
    try {
        const filter = {};

        if (req.query.urgency_level) filter.urgency_level = req.query.urgency_level;
        if (req.query.category) filter.category = req.query.category;
        if (req.query.location) filter.location = req.query.location;
        if (req.query.created_by) filter.created_by = req.query.created_by;

        const requests = await serviceRequest
            .find(filter)
            .populate("created_by", "name email");

        res.status(200).json({ status: true, data: requests });
    } catch (err) {
        res.status(500).json({ status: false, message: "Server error", error: err.message });
    }
};

export const getServiceRequestById = async (req, res) => {
    try {
        const request = await serviceRequest
            .findById(req.params.id)
            .populate("created_by", "name email");

        if (!request) {
            return res.status(404).json({ status: false, message: "Request not found" });
        }

        res.status(200).json({ status: true, data: request });
    } catch (err) {
        res.status(500).json({ status: false, message: "Server error", error: err.message });
    }
};

export const updateServiceRequest = async (req, res) => {
    try {
        const { error } = updateServiceRequestSchema.validate(req.body);
        if (error) {
            return res.status(400).json({ status: false, message: error.details[0].message });
        }

        const userId = req.user._id;
        const { id } = req.params;

        const request = await serviceRequest.findOneAndUpdate(
            { _id: id, created_by: userId },
            req.body,
            { new: true }
        );

        if (!request) {
            return res.status(404).json({ status: false, message: "Request not found or unauthorized" });
        }

        res.status(200).json({ status: true, message: "Updated successfully", data: request });
    } catch (err) {
        res.status(500).json({ status: false, message: "Server error", error: err.message });
    }
};

export const deleteServiceRequest = async (req, res) => {
    try {
        const userId = req.user._id;
        const { id } = req.params;

        const deleted = await serviceRequest.findOneAndDelete({
            _id: id,
            created_by: userId
        });

        if (!deleted) {
            return res.status(404).json({ status: false, message: "Request not found or unauthorized" });
        }

        res.status(200).json({ status: true, message: "Deleted successfully" });
    } catch (err) {
        res.status(500).json({ status: false, message: "Server error", error: err.message });
    }
};

export const updateStatus = async (req, res) => {
    try {
        const userId = req.user._id;
        const userType = req.user.userType;
        const serviceRequestId = req.params.id;
        const { status } = req.body;

        // Validate userType
        if (userType !== "service_provider") {
            return res.status(403).json({ status: false, message: "Only service providers can update status" });
        }

        // Validate status
        if (!["in_progress", "completed"].includes(status)) {
            return res.status(400).json({ status: false, message: "Invalid status update" });
        }

        const request = await serviceRequest.findById(serviceRequestId);

        if (!request) {
            return res.status(404).json({ status: false, message: "Service request not found" });
        }

        // Update status and optionally set accepted_by
        if (status === "in_progress" && !request.accepted_by) {
            request.accepted_by = userId;
        }

        request.status = status;
        await request.save();

        return res.status(200).json({
            status: true,
            message: `Status updated to ${status}`,
            data: request
        });

    } catch (error) {
        console.error("Error in updateStatus:", error);
        return res.status(500).json({
            status: false,
            message: "Internal server error"
        });
    }
};