<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('packages', function (Blueprint $table): void {
            if (! Schema::hasColumn('packages', 'package_type')) {
                $table->string('package_type', 32)->default(PackageType::Global->value)->after('category');
                $table->index('package_type');
            }
        });

        // Backfill: packages dominated by per-guest items become per_guest
        if (Schema::hasTable('package_items')) {
            $packageIds = DB::table('packages')->pluck('id');

            foreach ($packageIds as $packageId) {
                $items = DB::table('package_items')
                    ->leftJoin('products', 'products.id', '=', 'package_items.product_id')
                    ->where('package_items.package_id', $packageId)
                    ->selectRaw("COALESCE(package_items.charge_basis_override, products.default_charge_basis) as basis")
                    ->pluck('basis');

                if ($items->isEmpty()) {
                    continue;
                }

                $perGuestCount = $items->filter(fn ($b) => in_array($b, ['per_guest', 'per_guest_per_day'], true))->count();

                if ($perGuestCount > 0 && $perGuestCount >= ($items->count() / 2)) {
                    DB::table('packages')->where('id', $packageId)->update(['package_type' => PackageType::PerGuest->value]);
                }
            }
        }

        if (Schema::hasTable('settings')) {
            $now = now();
            DB::table('settings')->updateOrInsert(
                ['key' => 'schema_version'],
                ['value' => '1.000.001', 'is_encrypted' => false, 'created_at' => $now, 'updated_at' => $now],
            );
            DB::table('settings')->updateOrInsert(
                ['key' => 'app_version'],
                ['value' => '1.000.001', 'is_encrypted' => false, 'created_at' => $now, 'updated_at' => $now],
            );
        }
    }

    public function down(): void
    {
        Schema::table('packages', function (Blueprint $table): void {
            if (Schema::hasColumn('packages', 'package_type')) {
                $table->dropIndex(['package_type']);
                $table->dropColumn('package_type');
            }
        });
    }
};
