<?php
namespace App\Services;

use App\Models\Signalement;
use App\Models\Client;
use App\Models\Mission;
use App\Enums\StatutMission;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Auth\Access\AuthorizationException;
use InvalidArgumentException;

class SignalementService
{
    public function creerSignalement(Client $client, array $data): Signalement
    {
        $mission = Mission::with('besoin')->findOrFail($data['mission_id']);

        if ($mission->besoin->client_id !== $client->id) {
            throw new AuthorizationException('Cette mission ne vous appartient pas.');
        }

        $statut = $mission->statut instanceof StatutMission ? $mission->statut->value : $mission->statut;
        if ($statut !== StatutMission::ACTIVE->value) {
            throw new InvalidArgumentException('Cette mission n\'est pas active.');
        }

        $data['client_id'] = $client->id;
        $data['statut'] = 'recu';
        $data['priorite'] = $data['priorite'] ?? 'normale';

        return Signalement::create($data);
    }

    public function listerSignalementsClient(Client $client): LengthAwarePaginator
    {
        return Signalement::query()
            ->duClient($client->id)
            ->with(['mission.besoin'])
            ->orderBy('created_at', 'DESC')
            ->paginate(15);
    }

    public function getSignalementDuClient(Client $client, int $id): Signalement
    {
        return Signalement::where('id', $id)
            ->duClient($client->id)
            ->with(['mission.besoin'])
            ->firstOrFail();
    }
}
