<?php

namespace App\Http\Controllers;

use App\Http\Requests\ClientRequest;
use App\Http\Requests\RegisterClientRequest;
use App\Http\Resources\AuthResource;
use App\Http\Resources\ClientResource;
use App\Services\ClientService;
use Illuminate\Http\JsonResponse;

class ClientController extends Controller
{
    public function __construct(protected ClientService $service) {}

    public function index(): JsonResponse
    {
        $items = $this->service->getAll();

        return $this->successResponse(
            payload: ClientResource::collection($items),
        );
    }

    public function store(ClientRequest $request): JsonResponse
    {
        $item = $this->service->create($request->validated());

        return $this->successResponse(
            payload: new ClientResource($item),
            message: __('messages.created'),
            code:    201,
        );
    }

    public function show(int $id): JsonResponse
    {
        $item = $this->service->findById($id);

        return $this->successResponse(payload: new ClientResource($item));
    }

    public function update(ClientRequest $request, int $id): JsonResponse
    {
        $item = $this->service->update($request->validated(), $id);

        return $this->successResponse(
            payload: new ClientResource($item),
            message: __('messages.updated'),
        );
    }

    public function destroy(int $id): JsonResponse
    {
        $this->service->delete($id);

        return $this->successResponse(
            message: __('messages.deleted'),
            code:    204,
        );
    }

    //

    public function register(RegisterClientRequest $request): JsonResponse
    {
        $result = $this->service->register($request->validated());

        if (! $result) {
            return $this->errorResponse(message: __('auth.failed'), code: 401);
        }

        return $this->successResponse(
            payload: new AuthResource([
                ...data_get($result, 'payload'),
                'refresh_token' => data_get($result, 'refreshToken'),
            ]),
            message: __('auth.logged_in'),
        );
    }
}
