<?php

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

class CreateCoreReportDownloadTable extends Migration
{
    /** @var string */
    protected $tableName = 'core_report_download';

    /**
     * Create the durable request and lifecycle record used by queued report downloads.
     *
     * The source-specific request is kept in one JSON-compatible payload so Core can
     * support configured tables and trusted ad-hoc queries without adding a table for
     * every possible report parameter.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->tableName, function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id');
            $table->string('report_type');
            $table->longText('parameters');
            $table->string('format', 10);
            $table->string('file_path')->nullable();
            $table->string('status', 20);
            $table->unsignedTinyInteger('progress')->default(0);
            $table->unsignedBigInteger('row_count')->default(0);
            $table->unsignedInteger('retry_count')->default(0);
            $table->text('error_message')->nullable();
            $table->timestamp('queued_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamp('failed_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('user_id')
                ->on('core_user')
                ->onDelete('restrict')
                ->onUpdate('cascade');
            $table->index(['user_id', 'status']);
            $table->index(['status', 'created_at']);
            $table->index(['status', 'expires_at']);
        });
    }

    /**
     * Remove the report download infrastructure table.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->tableName);
    }
}
