<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Remove duplicates
        $duplicates = DB::table('playlist_episodes')
            ->select('playlist_id', 'episode_id', DB::raw('MIN(id) as keep_id'))
            ->groupBy('playlist_id', 'episode_id')
            ->havingRaw('COUNT(*) > 1')
            ->get();

        foreach ($duplicates as $dup) {
            DB::table('playlist_episodes')
                ->where('playlist_id', $dup->playlist_id)
                ->where('episode_id', $dup->episode_id)
                ->where('id', '!=', $dup->keep_id)
                ->delete();
        }

        // Fix index
        $playlistIds = Playlist::all()->pluck('id');
        foreach ($playlistIds as $playlistId) {
            $episodes = PlaylistEpisode::where('playlist_id', $playlistId)
                ->get();

            foreach ($episodes as $index => $episode) {
                $episode->position = $index + 1;
                $episode->save();
            }
        }

        // Make entries unique
        Schema::table('playlist_episodes', function (Blueprint $table) {
            $table->unique(['playlist_id', 'episode_id']);
        });
    }
};
