<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Delete entries with "#" as URL
        Downloads::where('url', '#')->delete();

        // Remove duplicate entries
        $duplicates = DB::table('downloads')
            ->select('episode_id', 'type', DB::raw('COUNT(*) as count'))
            ->groupBy('episode_id', 'type')
            ->having('count', '>', 1)
            ->get();

        foreach ($duplicates as $duplicate) {
            // Find all rows for this episode_id and type
            $rows = DB::table('downloads')
                ->where('episode_id', $duplicate->episode_id)
                ->where('type', $duplicate->type)
                ->orderBy('count', 'desc')  // Order by count to delete the ones with the lower count
                ->get();

            // Delete the rows with lower counts, keeping the one with the highest count
            $rows->skip(1)->each(function ($row) {
                DB::table('downloads')->where('id', $row->id)->delete();
            });
        }

        Schema::table('downloads', function (Blueprint $table) {
            $table->unique(['episode_id', 'type']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('downloads', function (Blueprint $table) {
            $table->dropUnique(['episode_id', 'type']);
        });
    }
};
