<?php

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

/**
 * mportal_share_grants — temporary record share with another provider (SIFA
 * Phase 8, patient_portal → medical_records → share_records).
 *
 * A patient (or staff on their behalf) issues a time-limited, tokenised grant so
 * an external provider can view a scope of the patient's data. `token` is a
 * random URL-safe string; the grant is valid while now() < expires_at AND
 * revoked_at IS NULL. business_id-scoped.
 *
 * NOTE: the external-provider VIEWING endpoint itself is thin/backlog (see
 * README) — this table + issue/revoke lifecycle is the delivered data layer.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_share_grants')) {
            return;
        }

        Schema::create('mportal_share_grants', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('patient_id');                 // clc_patients.id
            $t->string('shared_with', 191);                    // free text: provider name / email
            $t->enum('scope', ['records', 'appointments', 'full'])->default('records');
            $t->string('token', 64)->unique();
            $t->timestamp('expires_at')->nullable();
            $t->timestamp('revoked_at')->nullable();
            $t->unsignedInteger('created_by')->nullable();     // users.id
            $t->timestamps();

            $t->index(['business_id', 'patient_id'], 'mportal_share_biz_patient_idx');
        });
    }

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