<?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::create('companies', function (Blueprint $table) {
            $table->id();

            // Identificação
            $table->string('cnpj', 14)->unique();
            $table->string('razao_social');
            $table->string('nome_fantasia')->nullable();
            $table->string('ie', 20)->nullable();
            $table->string('uf', 2);
            $table->string('municipio')->nullable();
            $table->string('email')->nullable();
            $table->string('telefone', 20)->nullable();

            // Assinatura / SaaS
            $table->string('plano', 30)->default('trial');
            $table->boolean('is_active')->default(true);
            $table->date('assinatura_expira_em')->nullable();
            $table->unsignedInteger('limite_notas_mes')->default(1000);

            // Certificado digital A1
            $table->string('cert_path')->nullable();
            $table->text('cert_password')->nullable();       // encrypted cast
            $table->string('cert_cnpj', 14)->nullable();
            $table->string('cert_subject')->nullable();
            $table->timestamp('cert_valid_from')->nullable();
            $table->timestamp('cert_valid_to')->nullable();

            // Monitor DFe
            $table->boolean('monitor_enabled')->default(true);
            $table->unsignedInteger('monitor_intervalo_min')->default(60);
            $table->unsignedBigInteger('ult_nsu')->default(0);
            $table->unsignedBigInteger('max_nsu')->default(0);
            $table->boolean('manifestacao_automatica')->default(false);
            $table->unsignedTinyInteger('ambiente')->default(1); // 1=producao 2=homologacao
            $table->timestamp('last_sync_at')->nullable();
            $table->string('last_sync_status', 20)->nullable();
            $table->text('last_sync_message')->nullable();

            $table->timestamps();
            $table->softDeletes();

            $table->index(['is_active', 'monitor_enabled']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('companies');
    }
};
