<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('photos', function (Blueprint $table) {
            if (! Schema::hasColumn('photos', 'filename')) {
                $table->string('filename')->nullable()->after('guest_name');
            }

            if (! Schema::hasColumn('photos', 'original_name')) {
                $table->string('original_name')->nullable()->after('filename');
            }

            if (! Schema::hasColumn('photos', 'mime_type')) {
                $table->string('mime_type', 191)->nullable()->after('original_name');
            }

            if (! Schema::hasColumn('photos', 'size')) {
                $table->unsignedBigInteger('size')->nullable()->after('mime_type');
            }

            if (! Schema::hasColumn('photos', 'width')) {
                $table->unsignedInteger('width')->nullable()->after('thumbnail_path');
            }

            if (! Schema::hasColumn('photos', 'height')) {
                $table->unsignedInteger('height')->nullable()->after('width');
            }

            if (! Schema::hasColumn('photos', 'status')) {
                $table->string('status', 32)->default('pending')->after('height');
            }

            if (! Schema::hasColumn('photos', 'uploader_id')) {
                $table->foreignId('uploader_id')
                    ->nullable()
                    ->after('status')
                    ->constrained('users')
                    ->nullOnDelete();
            }

            if (! Schema::hasColumn('photos', 'ip_address')) {
                $table->string('ip_address', 45)->nullable()->after('uploader_id');
            }

            if (! Schema::hasColumn('photos', 'user_agent')) {
                $table->text('user_agent')->nullable()->after('ip_address');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('photos', function (Blueprint $table) {
            foreach (['user_agent', 'ip_address'] as $column) {
                if (Schema::hasColumn('photos', $column)) {
                    $table->dropColumn($column);
                }
            }

            if (Schema::hasColumn('photos', 'uploader_id')) {
                $table->dropConstrainedForeignId('uploader_id');
            }

            foreach (['status', 'height', 'width', 'size', 'mime_type', 'original_name', 'filename'] as $column) {
                if (Schema::hasColumn('photos', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
