<?php

use App\Models\Episode;
use App\Models\Hentai;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Change Tagging from Hentai to Episode
        $hentai = DB::table('hentai')->get();
        foreach ($hentai as $h) {

            $episodes = Episode::where('hentai_id', $h->id)->get();
            foreach ($episodes as $episode) {
                $episode->tag($h->tagNames());
            }
        }

        // Delete Hentai Tags
        foreach ($hentai as $h) {
            $h->untag();
        }

        Schema::table('episode', function (Blueprint $table) {
            $table->string('title')->after('id');
            $table->string('title_jpn')->after('title');
            $table->string('slug')->after('title_jpn');
            $table->integer('studios_id')->after('hentai_id');
            $table->date('release_date')->nullable()->after('legacy_stream');
        });

        $episodes = DB::table('episode')->get();
        foreach ($episodes as $episode) {
            $hentai = Hentai::where('id', $episode->hentai_id)->first();

            $episode->title = $hentai->title;
            $episode->title_jpn = $hentai->title_jpn;
            $episode->slug = $hentai->slug.'-'.$episode->episode;
            $episode->studios_id = $hentai->studios_id;
            $episode->release_date = Carbon::parse(strval($hentai->release_date).' 01:01:01');

            $alreadyexists = Episode::where('slug', $episode->slug)->first();
            if ($alreadyexists) {
                throw new RuntimeException('Migration stopped! Slug already exists: '.$episode->slug);
            }

            $episode->save();
        }

        // Remove
        Schema::table('hentai', function (Blueprint $table) {
            $table->dropColumn('title');
            $table->dropColumn('title_jpn');
            $table->dropColumn('episodes');
            $table->dropColumn('duration');
            $table->dropColumn('status');
            $table->dropColumn('score');
            $table->dropColumn('cover_url');
            $table->dropColumn('studios_id');
            $table->dropColumn('upload_date');
            $table->dropColumn('release_date');
        });
    }
};
