<?php

use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        if (! in_array(DB::getDriverName(), ['mysql', 'mariadb'], true)) {
            return;
        }

        $this->alterEnums(ProductLayout::values(), GroupLayout::values());
    }

    public function down(): void
    {
        if (! in_array(DB::getDriverName(), ['mysql', 'mariadb'], true)) {
            return;
        }

        $this->alterEnums(
            ['row', 'column_with_image', 'column_with_cart'],
            ['paginated', 'simple', 'simple_vertical', 'carousel'],
        );
    }

    /**
     * @param  list<string>  $productLayouts
     * @param  list<string>  $groupLayouts
     */
    private function alterEnums(array $productLayouts, array $groupLayouts): void
    {
        $products = $this->enumValues($productLayouts);
        $groups = $this->enumValues($groupLayouts);

        DB::statement("ALTER TABLE featured_groups MODIFY product_layout ENUM({$products}) NOT NULL");
        DB::statement("ALTER TABLE featured_groups MODIFY group_layout ENUM({$groups}) NOT NULL DEFAULT 'paginated'");
        DB::statement("ALTER TABLE tenants MODIFY search_product_layout ENUM({$products}) NOT NULL DEFAULT 'column_with_image'");
        DB::statement("ALTER TABLE tenants MODIFY search_group_layout ENUM({$groups}) NOT NULL DEFAULT 'paginated'");
    }

    /** @param list<string> $values */
    private function enumValues(array $values): string
    {
        return collect($values)
            ->map(fn (string $value): string => DB::getPdo()->quote($value))
            ->implode(',');
    }
};
