<?php

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

/**
 * PRC-194 — Logs table integrity (append-only forward hash chain).
 *
 * Adds two SHA-256 hex columns (64 chars each) to every log row:
 *   - prev_hash → row_hash of the immediately preceding log row (NULL for genesis)
 *   - row_hash  → SHA-256 over the canonical payload of THIS row + prev_hash
 *
 * The chain is computed by App\Observers\LogObserver on the "creating"
 * event so writes stay transparent for existing call sites. Update/Delete
 * are blocked at the same observer layer (append-only discipline).
 *
 * Backfill strategy: existing rows are left with NULL hashes; the
 * `logs:verify-chain` artisan command refuses to verify rows older
 * than the first row that has a non-null hash. Operators can run a
 * one-shot `logs:seal-existing` (optional follow-up) if a historical
 * seal is wanted.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('logs', function (Blueprint $table) {
            // SHA-256 hex = 64 chars; nullable for genesis row and pre-chain backfill window.
            $table->char('prev_hash', 64)->nullable()->after('session_id');
            $table->char('row_hash', 64)->nullable()->after('prev_hash');

            // row_hash should be unique once written (defensive — duplicates
            // would mean two identical canonical payloads, which is suspicious
            // for an audit log). Allow NULLs (pre-chain rows).
            $table->unique('row_hash', 'logs_row_hash_unique');
        });
    }

    public function down(): void
    {
        Schema::table('logs', function (Blueprint $table) {
            $table->dropUnique('logs_row_hash_unique');
            $table->dropColumn(['prev_hash', 'row_hash']);
        });
    }
};
