<?php

namespace App\Http\Controllers\API\DeliveryBoy;

use App\Http\Controllers\Controller;
use App\Models\DeliveryAssignment;
use App\Services\DeliveryMatchingService;
use Illuminate\Http\Request;

class AssignmentController extends Controller
{
    public function __construct(private DeliveryMatchingService $service)
    {
    }

    public function pending(Request $request)
    {
        $deliveryBoy = \App\Models\DeliveryBoy::where('user_id', $request->user()->id)->first();
        
        if (!$deliveryBoy) {
            return response()->json(['success' => true, 'data' => []]);
        }
        
        $assignments = DeliveryAssignment::with(['order.user', 'order.restaurant', 'order.items'])
            ->where('delivery_boy_id', $deliveryBoy->id)
            ->where('status', 'pending')
            ->orderBy('rank')
            ->get();
        
        return response()->json(['success' => true, 'data' => $assignments]);
    }

    public function accept(DeliveryAssignment $assignment)
    {
        if ($this->service->acceptAssignment($assignment)) {
            return response()->json(['success' => true, 'message' => 'Assignment accepted']);
        }
        
        return response()->json(['success' => false, 'message' => 'Assignment no longer available'], 409);
    }

    public function reject(Request $request, DeliveryAssignment $assignment)
    {
        $validated = $request->validate(['reason' => 'required|string|max:255']);
        
        $this->service->rejectAssignment($assignment, $validated['reason']);
        
        return response()->json(['success' => true, 'message' => 'Assignment rejected']);
    }
}
