<?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::create('update_settings', function (Blueprint $table): void {
            $table->id();
            $table->string('feed_url')->default('https://update.crm25.webnet.kz');
            $table->string('current_version')->default('1.005');
            $table->string('channel', 32)->default('stable');
            $table->boolean('is_active')->default(true);
            $table->boolean('auto_check_enabled')->default(true);
            $table->unsignedInteger('check_interval_minutes')->default(720);
            $table->unsignedInteger('request_timeout_seconds')->default(8);
            $table->boolean('verify_tls')->default(true);
            $table->timestamp('last_checked_at')->nullable();
            $table->string('last_remote_version')->nullable();
            $table->string('last_remote_build')->nullable();
            $table->text('last_error')->nullable();
            $table->json('meta')->nullable();
            $table->timestamps();
        });

        Schema::create('update_checks', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('update_setting_id')->constrained('update_settings')->cascadeOnDelete();
            $table->string('status', 32)->default('failed');
            $table->string('endpoint_url')->nullable();
            $table->unsignedInteger('http_status')->nullable();
            $table->boolean('is_update_available')->default(false);
            $table->string('remote_version')->nullable();
            $table->string('remote_build')->nullable();
            $table->text('error_message')->nullable();
            $table->json('payload')->nullable();
            $table->timestamp('checked_at')->nullable();
            $table->timestamps();

            $table->index(['status', 'checked_at']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('update_checks');
        Schema::dropIfExists('update_settings');
    }
};
