<?php

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

return new class extends Migration
{
    private const MENU_CODE = 'adminapp.desfile.entradas';

    private const TENANT_CODE = 'desfile_pura_tendencia';

    public function up(): void
    {
        if (! DB::table('menues')->where('code', 'main.adminapp')->exists()) {
            // Reference data is added by seeders on fresh installations.
            return;
        }

        $now = now();

        DB::transaction(function () use ($now): void {
            DB::table('menues')->updateOrInsert(
                ['code' => self::MENU_CODE],
                [
                    'label' => 'Entradas',
                    'parent_menu_code' => 'main.adminapp',
                    'content_type' => 'dynamic',
                    'static_content_schema' => null,
                    'route' => '/admin/desfile/entradas',
                    'created_at' => $now,
                    'updated_at' => $now,
                ],
            );

            if (DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
                DB::table('tenants_menues')->updateOrInsert(
                    [
                        'tenant_code' => self::TENANT_CODE,
                        'menu_code' => self::MENU_CODE,
                    ],
                    [
                        'static_content' => null,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ],
                );
            }

            DB::table('roles')
                ->whereIn('codigo', ['admin', 'adminapp'])
                ->pluck('codigo')
                ->each(function (string $roleCode): void {
                    DB::table('roles_menues')->updateOrInsert([
                        'rol_codigo' => $roleCode,
                        'menu_codigo' => self::MENU_CODE,
                    ]);
                });
        });
    }

    public function down(): void
    {
        DB::transaction(function (): void {
            DB::table('tenants_menues')
                ->where('tenant_code', self::TENANT_CODE)
                ->where('menu_code', self::MENU_CODE)
                ->delete();

            DB::table('roles_menues')
                ->where('menu_codigo', self::MENU_CODE)
                ->delete();

            DB::table('menues')
                ->where('code', self::MENU_CODE)
                ->delete();
        });
    }
};
