<?php

namespace App\Http\Controllers;

use App\Http\Requests\CartRequest;
use App\Http\Resources\CartResource;
use App\Services\CartService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    public function __construct(
        protected CartService $service,
    ) {}

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

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

    public function store(CartRequest $request): JsonResponse
    {
        $validated = $request->validated();

        $item = $this->hasSchedulePayload($validated)
            ? $this->service->createWithSchedules($validated)
            : $this->service->create($validated);

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

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

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

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

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

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

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

    //

    public function myCarts(): JsonResponse
    {
        $items = $this->service->getByUserId(Auth::id());

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

    public function storeMine(CartRequest $request): JsonResponse
    {
        $request->merge(['client_id' => Auth::user()?->client?->id]);

        $item = $this->service->createForUser($request->validated(), Auth::id());

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

    //

    private function hasSchedulePayload(array $data): bool
    {
        return ! empty($data['schedules'])
            || ! empty($data['dates'])
            || ! empty($data['date']);
    }
}
