<?php

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

/**
 * SIFA P3-T7 — appointment waitlist (spec §7 scheduling feature "waitlist:
 * automatic fill from cancellations").
 *
 * A patient who wants an appointment with a full doctor/day joins the waitlist.
 * When a matching slot opens (an appointment for that doctor/date is cancelled)
 * staff see the matching entries and can "book now" — which opens the normal
 * appointment create prefilled and marks the entry booked. If MedNotify is
 * installed, an 'appointment.slot_available' notification fans out to the
 * waitlisted patient's contact (fail-soft).
 *
 * business_id-scoped.
 *   status - waiting / offered / booked / cancelled / expired
 */
class CreateClcAppointmentWaitlistTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_appointment_waitlist')) return;

        Schema::create('clc_appointment_waitlist', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('patient_id');
            $table->unsignedInteger('contact_id')->nullable();
            $table->unsignedInteger('doctor_id')->nullable();
            $table->unsignedInteger('department_id')->nullable();
            $table->date('preferred_date')->nullable();
            $table->time('preferred_time_from')->nullable();
            $table->time('preferred_time_to')->nullable();
            $table->string('reason')->nullable();
            $table->enum('status', ['waiting', 'offered', 'booked', 'cancelled', 'expired'])->default('waiting');
            $table->unsignedInteger('offered_appointment_id')->nullable();
            $table->unsignedInteger('created_by')->nullable();
            $table->timestamps();

            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $table->foreign('patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            $table->index(['business_id', 'status', 'doctor_id']);
            $table->index(['business_id', 'preferred_date']);
        });
    }

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