<?php

namespace App\Domains\Catalog\Controllers\AdminApp;

use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
use App\Domains\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
use App\Domains\Catalog\Services\OnTicketFeaturedGroupService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class OnTicketFeaturedGroupController extends Controller
{
    public function __construct(
        private readonly OnTicketFeaturedGroupService $featuredGroupService,
    ) {}

    public function index(Request $request): AnonymousResourceCollection
    {
        return OnTicketFeaturedGroupResource::collection(
            $this->featuredGroupService->forTenant($this->onTicketTenant($request))
        );
    }

    public function store(UpsertOnTicketFeaturedGroupRequest $request): JsonResponse
    {
        $featuredGroup = $this->featuredGroupService->create(
            $this->onTicketTenant($request),
            $request->validated(),
        );

        return OnTicketFeaturedGroupResource::make($featuredGroup)
            ->response()
            ->setStatusCode(201);
    }

    public function update(
        UpsertOnTicketFeaturedGroupRequest $request,
        FeaturedGroup $featuredGroup,
    ): OnTicketFeaturedGroupResource {
        $tenant = $this->onTicketTenant($request);

        abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);

        return OnTicketFeaturedGroupResource::make(
            $this->featuredGroupService->update(
                $tenant,
                $featuredGroup,
                $request->validated(),
            )
        );
    }

    private function onTicketTenant(Request $request): Tenant
    {
        $tenant = $request->user()->tenant()->firstOrFail();

        abort_unless($tenant->website_type_code === 'onticket', 404);

        return $tenant;
    }
}
