<?php

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

/**
 * Task template engine (scenario 2.4): admin-defined per-department task
 * templates that auto-instantiate into concrete tasks when a booking is
 * confirmed, each with a due time relative to the event date.
 */
return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasTable('bms_task_templates')) {
            Schema::create('bms_task_templates', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->string('title', 191);
                $t->string('department', 40);                 // logistics, operations, kitchen, finance, sales…
                $t->string('event_type', 60)->nullable();     // null = all event types
                $t->integer('offset_days')->default(0);       // relative to event date (negative = before)
                $t->unsignedTinyInteger('offset_hour')->nullable(); // hour of day for due_at
                $t->string('assignee_role', 60)->nullable();
                $t->text('description')->nullable();
                $t->boolean('is_active')->default(true);
                $t->integer('sort_order')->default(0);
                $t->timestamps();
                $t->index(['business_id', 'is_active']);
            });
        }

        if (! Schema::hasTable('bms_tasks')) {
            Schema::create('bms_tasks', function (Blueprint $t) {
                $t->bigIncrements('id');
                $t->unsignedInteger('business_id');
                $t->unsignedBigInteger('booking_id');
                $t->unsignedBigInteger('template_id')->nullable();
                $t->string('title', 191);
                $t->string('department', 40);
                $t->dateTime('due_at')->nullable();
                $t->unsignedInteger('assignee_id')->nullable();  // ERP user
                $t->string('assignee_role', 60)->nullable();
                $t->enum('status', ['pending', 'in_progress', 'done', 'cancelled'])->default('pending');
                $t->dateTime('completed_at')->nullable();
                $t->unsignedInteger('completed_by')->nullable();
                $t->text('notes')->nullable();
                $t->timestamps();
                $t->index(['business_id', 'booking_id']);
                $t->index(['business_id', 'status']);
                $t->index(['assignee_id', 'status']);
            });
        }
    }

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