<?php

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

/**
 * mportal_messages — secure patient<->provider messaging (SIFA Phase 8,
 * patient_portal → communications).
 *
 * A thread is a set of rows sharing `thread_id` (a UUID). Each row is one
 * message from either the patient (sender_type=patient, sender_id=contacts.id)
 * or a staff member (sender_type=staff, sender_id=users.id). read_at is set when
 * the OTHER party opens the thread. business_id-scoped.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mportal_messages')) {
            return;
        }

        Schema::create('mportal_messages', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->uuid('thread_id');                             // groups a conversation
            $t->unsignedInteger('patient_id');                 // clc_patients.id (thread subject)
            $t->unsignedInteger('contact_id');                 // contacts.id (patient account holder)
            $t->enum('sender_type', ['patient', 'staff']);
            $t->unsignedInteger('sender_id');                  // contacts.id when patient, users.id when staff
            $t->text('body');
            $t->string('attachment_path', 255)->nullable();
            $t->timestamp('read_at')->nullable();
            $t->timestamps();

            $t->index(['business_id', 'thread_id'], 'mportal_msg_thread_idx');
            $t->index(['business_id', 'patient_id'], 'mportal_msg_biz_patient_idx');
            $t->index(['business_id', 'read_at'], 'mportal_msg_biz_read_idx');
        });
    }

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