<?php

declare(strict_types=1);

namespace App\Filament\Support;

use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Support\Exceptions\Halt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;

final class DberpDeleteRecordAction
{
    public static function configure(DeleteAction $action): DeleteAction
    {
        return $action->using(function (Model $record): bool {
            try {
                $deleted = $record->delete();

                if (! $deleted) {
                    Notification::make()
                        ->danger()
                        ->title((string) __('dberp.ui.record_delete_failed_title'))
                        ->body((string) __('dberp.ui.record_delete_returned_false_body'))
                        ->persistent()
                        ->send();

                    return false;
                }

                return true;
            } catch (Halt $halt) {
                throw $halt;
            } catch (QueryException $exception) {
                Notification::make()
                    ->danger()
                    ->title((string) __('dberp.ui.record_delete_failed_title'))
                    ->body(self::queryExceptionBody($exception))
                    ->persistent()
                    ->send();

                return false;
            }
        });
    }

    private static function queryExceptionBody(QueryException $exception): string
    {
        $message = $exception->getMessage();
        $sqlState = $exception->errorInfo[0] ?? '';

        if (
            $sqlState === '23000'
            || str_contains($message, '1451')
            || str_contains($message, 'Cannot delete')
            || str_contains($message, 'foreign key')
        ) {
            return (string) __('dberp.errors.record_delete_blocked_by_reference');
        }

        return (string) __('dberp.errors.record_delete_failed_generic');
    }
}
