<?php

use App\Models\Order;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->string('invoice_number', 32)->nullable()->unique()->after('number');
        });

        Order::query()
            ->whereNull('invoice_number')
            ->where('payment_status', Order::PAYMENT_PAID)
            ->orderBy('id')
            ->chunkById(200, function ($orders): void {
                foreach ($orders as $order) {
                    $year = $order->created_at?->format('Y') ?? now()->format('Y');
                    $order->invoice_number = sprintf('FAC-%s-%06d', $year, (int) $order->id);
                    $order->saveQuietly();
                }
            });
    }

    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropUnique(['invoice_number']);
            $table->dropColumn('invoice_number');
        });
    }
};

