<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreAgentRequest;
use App\Http\Requests\Api\UpdateAgentRequest;
use App\Http\Resources\AgentResource;
use App\Models\Agent;
use App\Models\User;
use App\Services\AgentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;

class AgentController extends Controller
{
    public function __construct(private AgentService $agents) {}

    public function index(): AnonymousResourceCollection
    {
        return AgentResource::collection(
            Agent::query()
                ->with(['creator'])
                ->withCount('customers')
                ->latest('id')
                ->get(),
        );
    }

    public function store(StoreAgentRequest $request): JsonResponse
    {
        $actor = $request->user();

        assert($actor instanceof User);

        $agent = $this->agents->create($actor, $request->payload());

        return AgentResource::make($agent->loadMissing('creator')->loadCount('customers'))
            ->response()
            ->setStatusCode(201);
    }

    public function show(Agent $agent): AgentResource
    {
        return AgentResource::make(
            $agent->loadMissing(['creator', 'customers'])->loadCount('customers'),
        );
    }

    public function update(UpdateAgentRequest $request, Agent $agent): AgentResource
    {
        $agent = $this->agents->update($agent, $request->payload());

        return AgentResource::make(
            $agent->loadMissing(['creator', 'customers'])->loadCount('customers'),
        );
    }

    public function destroy(Agent $agent): Response
    {
        $this->agents->delete($agent);

        return response()->noContent();
    }
}
