<?php

use App\Domains\Event\Services\EventDateTextFormatter;
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('tenants', function (Blueprint $table): void {
            $table->text('event_date_text')->nullable()->after('event_location');
        });

        $formatter = new EventDateTextFormatter;

        DB::table('tenants')->orderBy('id')->each(function (object $tenant) use ($formatter): void {
            $dates = DB::table('event_dates')
                ->where('tenant_code', $tenant->codigo)
                ->orderBy('date')
                ->pluck('date');

            DB::table('tenants')->where('id', $tenant->id)->update([
                'event_date_text' => $formatter->format($dates),
            ]);
        });
    }

    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table): void {
            $table->dropColumn('event_date_text');
        });
    }
};
