<?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::table('job_sources', function (Blueprint $table): void {
            if (! Schema::hasColumn('job_sources', 'request_method')) {
                $table->string('request_method', 20)->default('get');
            }

            if (! Schema::hasColumn('job_sources', 'auth_type')) {
                $table->string('auth_type', 40)->default('none');
            }

            if (! Schema::hasColumn('job_sources', 'auth_header_name')) {
                $table->string('auth_header_name')->nullable();
            }

            if (! Schema::hasColumn('job_sources', 'auth_username')) {
                $table->string('auth_username')->nullable();
            }

            if (! Schema::hasColumn('job_sources', 'auth_secret')) {
                $table->text('auth_secret')->nullable();
            }

            if (! Schema::hasColumn('job_sources', 'request_headers')) {
                $table->json('request_headers')->nullable();
            }

            if (! Schema::hasColumn('job_sources', 'query_parameters')) {
                $table->json('query_parameters')->nullable();
            }

            if (! Schema::hasColumn('job_sources', 'sync_frequency')) {
                $table->string('sync_frequency', 40)->default('manual')->index();
            }

            if (! Schema::hasColumn('job_sources', 'rate_limit_per_minute')) {
                $table->unsignedInteger('rate_limit_per_minute')->nullable();
            }

            if (! Schema::hasColumn('job_sources', 'notes')) {
                $table->text('notes')->nullable();
            }
        });
    }

    public function down(): void
    {
        Schema::table('job_sources', function (Blueprint $table): void {
            foreach ([
                'request_method',
                'auth_type',
                'auth_header_name',
                'auth_username',
                'auth_secret',
                'request_headers',
                'query_parameters',
                'sync_frequency',
                'rate_limit_per_minute',
                'notes',
            ] as $column) {
                if (Schema::hasColumn('job_sources', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
