<?php

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

/**
 * SSL certificates registry (PRC-57).
 *
 * Lifecycle is tracked with three orthogonal flags rather than a single
 * status enum:
 *   - `installed`   = cert is provisioned and downloadable
 *   - `revoked_at`  = explicitly revoked (set timestamp)
 *   - `expires_at`  = billing-period end (NOT the CA TTL); when in the
 *                     past, the cert is considered expired regardless of
 *                     whether a CA refresh happened internally
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('client_ssl_certificates', function (Blueprint $t) {
            $t->id();
            $t->foreignId('client_product_id')
                ->constrained('client_products', indexName: 'cssl_cp_idx')
                ->cascadeOnDelete();
            $t->foreignId('client_id')
                ->constrained('clients', indexName: 'cssl_client_idx')
                ->cascadeOnDelete();

            // Identity
            $t->string('common_name');
            $t->json('alt_names')->nullable();
            $t->string('module', 64);

            // State (booleans + timestamps — no enum)
            $t->boolean('installed')->default(false);
            $t->timestamp('installed_at')->nullable();
            $t->timestamp('expires_at')->nullable();
            $t->timestamp('revoked_at')->nullable();

            // Customer-supplied installation input (CSR, org info,
            // validation email, ...). Schema is module-driven via
            // AbstractSsl::customerInputSchema().
            $t->json('installation_input')->nullable();

            // Cert material (filled when installed)
            $t->string('issuer')->nullable();
            $t->text('csr')->nullable();
            $t->text('certificate')->nullable();
            $t->text('certificate_chain')->nullable();
            $t->text('private_key')->nullable();        // Crypt-encrypted
            $t->boolean('private_key_downloaded')->default(false);

            // Provider-side opaque blob (ACME order url, CA order id, ...)
            $t->json('module_data')->nullable();

            // Last failure observability
            $t->text('last_error')->nullable();
            $t->timestamp('last_attempt_at')->nullable();

            $t->timestamps();

            $t->index('expires_at', 'cssl_expires_idx');
            $t->index(['installed', 'expires_at'], 'cssl_installed_expires_idx');
        });
    }

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