<?php

declare(strict_types=1);

namespace App\Application\Admin\Content;

use App\Application\Admin\Service\AdminLayoutProcessor;
use App\Domain\Media\ImageSlot;
use App\Domain\Media\ImageSlotRepository;
use App\Framework\Attributes\Route;
use App\Framework\Auth\Auth;
use App\Framework\DateTime\Clock;
use App\Framework\Http\Method;
use App\Framework\Http\Request;
use App\Framework\Meta\MetaData;
use App\Framework\Router\Result\ViewResult;

final readonly class ImageSlotsController
{
    public function __construct(
        private ImageSlotRepository $imageSlotRepository,
        private AdminLayoutProcessor $layoutProcessor,
        private Clock $clock,
    ) {
    }

    #[Auth]
    #[Route('/admin/content/image-slots', name: 'admin.content.image-slots')]
    public function show(): ViewResult
    {
        $slots = $this->imageSlotRepository->getSlots();

        $data = [
            'title' => 'Image Slots',
            'slots' => $slots,
            'current_year' => $this->clock->now()->format('Y'),
        ];

        $finalData = $this->layoutProcessor->processLayoutFromArray($data);

        return new ViewResult('imageslots', new MetaData('Image Slots', 'Image Slots Management'), $finalData);
    }

    #[Auth]
    #[Route('/admin/content/image-slots/{slotName}', method: Method::POST)]
    public function update(string $slotName): ViewResult
    {
        $slot = $this->imageSlotRepository->findBySlotName(urldecode($slotName));

        $data = [
            'title' => 'Edit Image Slot',
            'slotName' => $slot->slotName,
            'id' => $slot->id,
            'current_year' => $this->clock->now()->format('Y'),
        ];

        $finalData = $this->layoutProcessor->processLayoutFromArray($data);

        return new ViewResult('imageslot', new MetaData('Edit Image Slot', 'Image Slot Management'), $finalData);
    }

    #[Auth]
    #[Route('/admin/imageslots/create', method: Method::POST)]
    public function create(Request $request): void
    {
        $name = $request->parsedBody->get('slotName');

        $slot = new ImageSlot(0, $name, '');

        $this->imageSlotRepository->save($slot);

        // TODO: Return proper response or redirect
    }

    #[Auth]
    #[Route('/admin/imageslots/edit/{id}', method: Method::PUT)]
    public function edit(Request $request, string $id): void
    {
        $name = $request->parsedBody->get('slotName');

        $slot = $this->imageSlotRepository->findById((int)$id);


        $slot = new ImageSlot($slot->id, $name, $slot->imageId);

        $this->imageSlotRepository->save($slot);
    }
}
