<?php

namespace App\Domains\FiestaFutbolInfantil\Controllers;

use App\Domains\FiestaFutbolInfantil\Requests\UpsertMerchandiseRequest;
use App\Domains\FiestaFutbolInfantil\Resources\MerchandiseResource;
use App\Domains\FiestaFutbolInfantil\Services\MerchandiseService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;

class MerchandiseController extends Controller
{
    public function __construct(private readonly MerchandiseService $merchandiseService) {}

    public function index(Request $request): AnonymousResourceCollection
    {
        return MerchandiseResource::collection(
            $this->merchandiseService->all($request->user()->tenant()->firstOrFail())
        );
    }

    public function store(UpsertMerchandiseRequest $request): JsonResponse
    {
        $tenant = $request->user()->tenant()->firstOrFail();
        $items = $this->merchandiseService->upsertMany(
            $tenant,
            $request->validated('items'),
        );

        return MerchandiseResource::collection($items)
            ->response()
            ->setStatusCode(200);
    }

    public function destroy(Request $request, int $merchandise): Response
    {
        $this->merchandiseService->delete(
            $request->user()->tenant()->firstOrFail(),
            $merchandise,
        );

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