<?php

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

class CreatePcSettingsAndJobsTables extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('pc_settings')) {
            Schema::create('pc_settings', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('key', 64)->unique();
                $table->text('value')->nullable();
                $table->timestamps();
            });
        }

        if (! Schema::hasTable('pc_jobs')) {
            Schema::create('pc_jobs', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedInteger('business_id')->nullable();
                $table->string('type', 32);                  // parse | enrich_has | enrich_missing
                $table->string('status', 16)->default('running'); // running | done | stopped | error
                $table->unsignedInteger('total')->default(0);
                $table->unsignedInteger('processed')->default(0);
                $table->unsignedInteger('matched')->default(0);
                $table->unsignedInteger('added_parts')->default(0);
                $table->unsignedInteger('added_devices')->default(0);
                $table->unsignedInteger('added_barcodes')->default(0);
                $table->unsignedInteger('cursor')->default(0); // last product id processed
                $table->string('trigger', 16)->default('ui');  // ui | schedule
                $table->text('message')->nullable();
                $table->timestamp('started_at')->nullable();
                $table->timestamp('finished_at')->nullable();
                $table->timestamps();

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

    public function down()
    {
        Schema::dropIfExists('pc_jobs');
        Schema::dropIfExists('pc_settings');
    }
}
