<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('playlists', function (Blueprint $table) {
            $table->string('share_token', 64)->nullable()->unique()->after('is_default');
        });

        // Backfill tokens for existing playlists
        Playlist::whereNull('share_token')->each(function ($playlist) {
            $playlist->updateQuietly(['share_token' => Str::random(32)]);
        });
    }

    public function down(): void
    {
        Schema::table('playlists', function (Blueprint $table) {
            $table->dropColumn('share_token');
        });
    }
};
