<?php

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

/**
 * SSL Certificates — Let's Encrypt + custom upload
 *
 * Phase 1 Epic 9
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('ssl_certificates', function (Blueprint $table) {
            $table->id();

            $table->foreignId('domain_id')
                ->constrained('domains')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();

            $table->enum('issuer', ['lets-encrypt', 'custom', 'self-signed'])->default('lets-encrypt');
            $table->enum('challenge', ['http-01', 'dns-01'])->default('http-01');
            $table->text('certificate')->nullable()->comment('PEM');
            $table->text('private_key')->nullable()->comment('PEM (encrypted at rest)');
            $table->text('chain')->nullable();

            $table->string('common_name');
            $table->json('alt_names')->nullable()->comment('SAN list');
            $table->timestamp('issued_at')->nullable();
            $table->timestamp('expires_at')->nullable();

            $table->enum('status', ['pending', 'provisioning', 'active', 'expired', 'error', 'renewing'])->default('pending');
            $table->text('last_error')->nullable();
            $table->timestamp('last_renewal_attempt_at')->nullable();
            $table->boolean('auto_renew')->default(true);

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

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

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