<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Inside\Content\Contracts\SchemaService;
use Inside\Content\Facades\Schema;
use Inside\Database\Migrations\HasConsole;

final class RemoveCorruptBr extends Migration
{
    use HasConsole;

    public function up(): void
    {
        $service = App::make(SchemaService::class);

        $this->writeln("\n<fg=red>Remove Corrupt br in Wysiwyg</>\n");

        foreach ($service->getAllFieldsListingOfType('wysiwyg') as $type => $fieldNames) {
            $fieldNames = collect($fieldNames);

            $table = match (Schema::isSectionType($type)) {
                true => section_type_to_table($type),
                default => type_to_table($type)
            };

            if (! $table) {
                continue;
            }

            $corrupted = DB::table($table)
                ->where(fn (Builder $query) => $fieldNames->each(fn ($field) => $query->orWhere($field, 'like', '%<p class="ds-base-text-container"><br /></p>%')))
                ->get();

            $this->writeln('<fg=blue>Table</>: '.$table);
            $this->writeln('<fg=magenta>Fields</>: '.$fieldNames->join(' '));
            $this->writeln('<fg=yellow>Find '.$corrupted->count().' potential corrupted rows</>');

            $corrupted->transform(fn ($row) => $this->removeCorruptBr($table, $row, $fieldNames));

            $this->writeln('<fg=green>Fixed '.$corrupted->filter()->count()." corrupted rows</>\n");
        }
    }

    private function removeCorruptBr(string $table, Object $row, Collection $fieldNames): bool
    {
        $fieldNames->each(fn ($field) => $row->{$field} = str_replace('<p class="ds-base-text-container"><br /></p>', '<p class="ds-base-text-container"></p>', $row->{$field}));

        DB::table($table)->where('uuid', $row->uuid)->update(collect($row)->only($fieldNames)->toArray());

        $this->writeln('  UUID: '.$row->uuid);

        return true;
    }
}
