<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Dispute;
use App\Models\DisputeEvent;
use App\Services\BookingStateService;
use Illuminate\Http\Request;
use App\Notifications\DisputeOpened;

class DisputeController extends Controller
{
    public function store(Booking $booking, Request $request, BookingStateService $state)
    {
        $this->authorize('view', $booking);
        $data = $request->validate([
            'reason' => ['required', 'string'],
            'details' => ['nullable', 'string'],
        ]);

        $dispute = Dispute::create([
            'booking_id' => $booking->id,
            'opened_by' => $request->user()->id,
            'reason' => $data['reason'],
            'details' => $data['details'] ?? null,
            'status' => 'open',
            'opened_at' => now(),
        ]);

        $state->transition($booking, 'disputed');
        DisputeEvent::create([
            'dispute_id' => $dispute->id,
            'user_id' => $request->user()->id,
            'action' => 'opened',
            'notes' => $data['reason'],
        ]);
        $booking->provider?->notify(new DisputeOpened($dispute));
        $booking->customer?->notify(new DisputeOpened($dispute));

        return back()->with('status', 'Dispute opened.');
    }
}
