<?php

namespace App\Http\Controllers\Api\Gallery;

use App\Exceptions\ApiHttpException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Gallery\GallerySectionUpdateRequest;
use App\Http\Requests\Api\Gallery\UpdateOrderRequest;
use App\Http\Resources\Gallery\GallerySection as GallerySectionResource;
use App\Services\GalleryService;

class GallerySectionController extends Controller
{
    private $galleryService;

    /**
     * Create a new GalleryController instance.
     *
     * @return void
     */
    public function __construct(GalleryService $galleryService)
    {
        $this->galleryService = $galleryService;
    }

    public function update(GallerySectionUpdateRequest $request)
    {
        $validatedData = $request->validated();
        $account = auth()->user()->mainAccount;
        $gallery = $account->galleries()->where('uid', $request->route('galleryUid'))->first();
        if ($gallery === null) {
            throw new ApiHttpException(403, 'forbidden');
        }
        $gallerySection = $gallery->gallerySections()->where('uid', $request->route('sectionUid'))->first();
        if ($gallerySection === null) {
            throw new ApiHttpException(403, 'forbidden');
        }
        $this->galleryService->updateGallerySection($gallerySection, $validatedData);

        return response()->json(new GallerySectionResource($gallerySection));
    }

    public function updateOrder(UpdateOrderRequest $request)
    {
        $validatedData = $request->validated();
        $account = auth()->user()->mainAccount;
        $gallery = $account->galleries()->where('uid', $request->route('galleryUid'))->first();
        if ($gallery === null) {
            throw new ApiHttpException(403, 'forbidden');
        }
        $gallerySection = $gallery->gallerySections()->where('uid', $request->route('sectionUid'))->first();
        if ($gallerySection === null) {
            throw new ApiHttpException(403, 'forbidden');
        }
        $this->galleryService->updateGallerySectionOrder($gallerySection, $validatedData['itemOrder']);

        return response()->json(new GallerySectionResource($gallerySection));
    }
}
