<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Hentai;

use App\Jobs\DiscordReleaseNotification;
use App\Services\DownloadService;
use App\Services\EpisodeService;
use App\Services\GalleryService;
use Illuminate\Http\Request;

class ReleaseController extends Controller
{
    protected EpisodeService $episodeService;
    protected GalleryService $galleryService;
    protected DownloadService $downloadService;

    public function __construct(
        EpisodeService $episodeService, 
        GalleryService $galleryService, 
        DownloadService $downloadService
    )  {
        $this->episodeService = $episodeService;
        $this->galleryService = $galleryService;
        $this->downloadService = $downloadService;
    }

    /** 
     * Display release page
     */
    public function index(): \Illuminate\View\View
    {
        return view('admin.release.create');
    }

    /**
     * Upload New Hentai with One or Multipe Episodes
     */
    public function store(Request $request): \Illuminate\Http\RedirectResponse
    {
        // Create new Hentai or find existing one
        $slug = $this->episodeService->generateSlug($request->input('title'));

        $hentai = Hentai::where('slug', $slug)->first();

        // If hentai exists and was created today, return to home
        if ($hentai?->created_at->isToday()) {
            return to_route('home.index');
        }

        // If hentai does not exist, create a new instance
        $hentai = Hentai::firstOrCreate(
            ['slug' => $slug],
            ['description' => $request->input('description1')]
        );

        // Studio
        $studio = $this->episodeService->getOrCreateStudio(json_decode($request->input('studio'))[0]->value);

        // Create Episode(s)
        $releasedEpisodes = [];
        for ($i = 1; $i <= $request->input('episodes'); $i++) {

            $episode = $this->episodeService->createEpisode($request, $hentai, $i, $studio);

            $this->episodeService->createOrUpdateCover($request, $episode, $slug, $i);
            $this->downloadService->createOrUpdateDownloads($request, $episode, $i);
            $this->galleryService->createOrUpdateGallery($request, $hentai, $episode, $i);

            $releasedEpisodes[] = $episode->slug;
        }

        foreach ($releasedEpisodes as $slug) {
            // Dispatch Discord Alert
            DiscordReleaseNotification::dispatch($slug, 'release');
        }

        cache()->flush();

        return to_route('home.index');
    }
}
