<?php

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

/**
 * Phase 3: org shift templates + duty roster entries (unit × date × shift).
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('care_shifts', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->constrained('care_organizations')->cascadeOnDelete();
            $table->string('code'); // day, evening, night, custom…
            $table->string('label');
            $table->time('start_time');
            $table->time('end_time');
            $table->string('color')->nullable();
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['organization_id', 'code']);
            $table->index(['organization_id', 'is_active']);
        });

        Schema::create('care_roster_entries', function (Blueprint $table) {
            $table->id();
            $table->string('owner_ref')->index();
            $table->foreignId('organization_id')->constrained('care_organizations')->cascadeOnDelete();
            $table->foreignId('care_unit_id')->constrained('care_care_units')->cascadeOnDelete();
            $table->foreignId('shift_id')->constrained('care_shifts')->cascadeOnDelete();
            $table->foreignId('member_id')->constrained('care_members')->cascadeOnDelete();
            $table->date('duty_date');
            /** scheduled | confirmed | completed | cancelled */
            $table->string('status')->default('scheduled');
            $table->foreignId('staff_assignment_id')->nullable()
                ->constrained('care_staff_assignments')->nullOnDelete();
            $table->text('notes')->nullable();
            $table->string('created_by')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['care_unit_id', 'shift_id', 'member_id', 'duty_date'], 'care_roster_unit_shift_member_date');
            $table->index(['care_unit_id', 'duty_date']);
            $table->index(['member_id', 'duty_date']);
            $table->index(['organization_id', 'duty_date']);
        });
    }

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