<?php

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

return new class extends Migration
{
    /**
     * A receipt is only useful if you can prove where it came from. The
     * original attachment columns stored a path and a filename and nothing
     * else — not the disk it landed on, not the type, not who put it there.
     */
    public function up(): void
    {
        if (!Schema::hasTable('expenses')) {
            return;
        }

        Schema::table('expenses', function (Blueprint $table) {
            if (!Schema::hasColumn('expenses', 'attachment_disk')) {
                $table->string('attachment_disk', 32)->nullable()->after('attachment_name');
            }
            if (!Schema::hasColumn('expenses', 'attachment_mime')) {
                $table->string('attachment_mime', 128)->nullable()->after('attachment_disk');
            }
            if (!Schema::hasColumn('expenses', 'attachment_size')) {
                $table->unsignedBigInteger('attachment_size')->nullable()->after('attachment_mime');
            }
            if (!Schema::hasColumn('expenses', 'attachment_uploaded_by')) {
                $table->foreignId('attachment_uploaded_by')->nullable()->after('attachment_size')
                    ->constrained('users')->nullOnDelete();
            }
            if (!Schema::hasColumn('expenses', 'attachment_uploaded_at')) {
                $table->timestamp('attachment_uploaded_at')->nullable()->after('attachment_uploaded_by');
            }
        });

        // Rows written before this migration stored their file on the `public`
        // disk. Record that, so the streaming controller reads them from the
        // disk they actually live on instead of guessing.
        if (Schema::hasColumn('expenses', 'attachment_disk')) {
            \Illuminate\Support\Facades\DB::table('expenses')
                ->whereNotNull('attachment_path')
                ->whereNull('attachment_disk')
                ->update(['attachment_disk' => 'public']);
        }
    }

    public function down(): void
    {
        if (!Schema::hasTable('expenses')) {
            return;
        }

        Schema::table('expenses', function (Blueprint $table) {
            if (Schema::hasColumn('expenses', 'attachment_uploaded_by')) {
                $table->dropConstrainedForeignId('attachment_uploaded_by');
            }
            foreach (['attachment_disk', 'attachment_mime', 'attachment_size', 'attachment_uploaded_at'] as $column) {
                if (Schema::hasColumn('expenses', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
