<?php

use App\Models\Downloads;
use App\Models\Episode;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('downloads', function (Blueprint $table) {
            $table->id();
            $table->foreignId('episode_id')->index()->constrained()->cascadeOnDelete();
            $table->char('type', 5);
            $table->string('url');
            $table->double('size')->nullable();
            $table->timestamps();
        });

        // Migrate old entries
        foreach (Episode::all() as $episode) {
            // 1080p
            if (! empty($episode->download_url)) {
                Downloads::create([
                    'episode_id' => $episode->id,
                    'type' => 'FHD',
                    'url' => $episode->download_url,
                ]);
            }

            // 1080p48
            if (! empty($episode->download_url_interpolated)) {
                Downloads::create([
                    'episode_id' => $episode->id,
                    'type' => 'FHDi',
                    'url' => $episode->download_url_interpolated,
                ]);
            }

            // 2160p
            if (! empty($episode->download_url_4k)) {
                Downloads::create([
                    'episode_id' => $episode->id,
                    'type' => 'UHD',
                    'url' => $episode->download_url_4k,
                ]);
            }
        }

        // Drop old entries
        Schema::table('episodes', function (Blueprint $table) {
            $table->dropColumn('download_url_interpolated');
            $table->dropColumn('download_url_4k');
            $table->dropColumn('download_url');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('downloads');
    }
};
