<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('upload_batches', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('name', 160)->nullable();
            $table->string('status', 32)->default('uploading')->index();
            $table->unsignedInteger('total_items')->default(0);
            $table->unsignedInteger('processed_items')->default(0);
            $table->unsignedInteger('failed_items')->default(0);
            $table->unsignedInteger('published_items')->default(0);
            $table->json('defaults_json')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'created_at'], 'upload_batches_user_created_idx');
        });

        Schema::create('upload_batch_items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->foreignId('upload_batch_id')->constrained('upload_batches')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('artwork_id')->nullable()->constrained('artworks')->nullOnDelete();
            $table->string('original_filename');
            $table->string('status', 32)->default('uploaded')->index();
            $table->string('processing_stage', 32)->default('queued')->index();
            $table->string('error_code', 64)->nullable();
            $table->text('error_message')->nullable();
            $table->unsignedTinyInteger('metadata_completeness')->default(0);
            $table->boolean('is_ready_to_publish')->default(false)->index();
            $table->timestamp('uploaded_at')->nullable();
            $table->timestamp('processed_at')->nullable();
            $table->timestamp('published_at')->nullable();
            $table->timestamps();

            $table->index(['upload_batch_id', 'status'], 'upload_batch_items_batch_status_idx');
            $table->index(['user_id', 'status'], 'upload_batch_items_user_status_idx');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('upload_batch_items');
        Schema::dropIfExists('upload_batches');
    }
};