<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Add scheduled-publishing columns to artworks table.
 *
 * Fields added:
 *   - publish_at    Nullable UTC datetime – when the artwork becomes public (scheduled publish)
 *   - artwork_status  Enum string: draft | scheduled | published | archived
 *   - artwork_timezone  Nullable IANA timezone string for display purposes only
 *
 * Note: we use `artwork_status` to avoid collision with any reserved word `status`
 * across DB adapters. A DB-level check constraint enforces valid values.
 *
 * Rules:
 *   - publish_at set in the future  → artwork_status = 'scheduled'
 *   - scheduler job publishes when publish_at <= now():
 *     sets published_at = now(), artwork_status = 'published'
 *   - Immediate publish keeps existing flow (published_at = now(), artwork_status = 'published')
 *   - Draft state is pre-publish (artwork_status = 'draft', published_at = null)
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::table('artworks', function (Blueprint $table) {
            // When this artwork should become publicly visible (UTC)
            $table->dateTime('publish_at')->nullable()->after('published_at');

            // Lifecycle status
            $table->string('artwork_status', 20)->default('draft')->after('publish_at');

            // User's display timezone (IANA), stored for UX display only
            $table->string('artwork_timezone', 50)->nullable()->after('artwork_status');

            // Index for scheduler job: find artworks whose publish_at has passed
            $table->index(['artwork_status', 'publish_at'], 'idx_artworks_scheduled_publish');
        });
    }

    public function down(): void
    {
        Schema::table('artworks', function (Blueprint $table) {
            $table->dropIndex('idx_artworks_scheduled_publish');
            $table->dropColumn(['publish_at', 'artwork_status', 'artwork_timezone']);
        });
    }
};
