<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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');
    }
}
