<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('order_items', function (Blueprint $table) {
            $table->string('production_status')->default('pending')->after('finishing_note');
            $table->timestamp('item_started_at')->nullable()->after('production_status');
            $table->timestamp('item_finished_at')->nullable()->after('item_started_at');
        });

        // Backfill existing items from parent order status
        DB::statement("
            UPDATE order_items
            SET production_status = (
                SELECT COALESCE(orders.production_status, 'pending')
                FROM orders
                WHERE orders.id = order_items.order_id
            ),
            item_started_at = (
                SELECT orders.started_at
                FROM orders
                WHERE orders.id = order_items.order_id
            ),
            item_finished_at = (
                SELECT orders.finished_at
                FROM orders
                WHERE orders.id = order_items.order_id
            )
        ");
    }

    public function down(): void
    {
        Schema::table('order_items', function (Blueprint $table) {
            $table->dropColumn(['production_status', 'item_started_at', 'item_finished_at']);
        });
    }
};
