<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

class CreateClcAppointmentEditRequestsTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_appointment_edit_requests')) {
            Schema::create('clc_appointment_edit_requests', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->unsignedInteger('appointment_id')->index();
                $table->unsignedInteger('requested_by')->index();
                $table->text('reason');
                $table->enum('status', ['pending', 'approved', 'rejected'])->default('pending')->index();
                $table->unsignedInteger('reviewed_by')->nullable();
                $table->timestamp('reviewed_at')->nullable();
                $table->text('review_notes')->nullable();
                $table->timestamp('consumed_at')->nullable(); // set when the single approved edit is used
                $table->timestamps();
            });
        }

        // Permissions for the post-completion edit workflow
        foreach ([
            'clinic.edit_completed_appointments',
            'clinic.approve_edit_requests',
        ] as $perm) {
            Permission::findOrCreate($perm, 'web');
        }
    }

    public function down()
    {
        Schema::dropIfExists('clc_appointment_edit_requests');

        Permission::whereIn('name', [
            'clinic.edit_completed_appointments',
            'clinic.approve_edit_requests',
        ])->delete();
    }
}
