<?php

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

/**
 * Pessimistic project-edit lock (Team Workspaces P4 / Δ21).
 *
 * One row per project (`project_id` UNIQUE) records the current editor.
 * A second user lands read-only with a "{name} is editing · Take over"
 * banner. Acquire / takeover are transactional (`lockForUpdate` on the row);
 * a row whose `last_heartbeat_at` is older than `LOCK_TTL` (45s) is treated
 * as free on the next acquire (expiry-on-read — correctness does not depend
 * on the prune sweep running).
 *
 * Applies in BOTH modes: a solo self-hosted buyer simply always holds the
 * lock (one cheap heartbeat while the editor tab is visible). Replaces the
 * dropped `screens.revision` / `screen_presence` ideas — a single-editor
 * lock needs neither.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('project_edit_locks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('project_id')->unique()->constrained('projects')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->timestamp('acquired_at')->nullable();
            $table->timestamp('last_heartbeat_at')->nullable()->index();
            $table->timestamps();
        });
    }

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