<?php

namespace App\Support;

class AdminFlash
{
    /**
     * @return array{success:string, success_link_href?:string, success_link_label?:string}
     */
    public static function success(string $message, string $linkHref = '', string $linkLabel = '查看'): array
    {
        $message = (string) $message;
        $linkHref = trim((string) $linkHref);
        $linkLabel = trim((string) $linkLabel);

        $payload = [
            'success' => $message,
        ];

        if ($linkHref !== '') {
            $payload['success_link_href'] = $linkHref;
            $payload['success_link_label'] = $linkLabel !== '' ? $linkLabel : '查看';
        }

        return $payload;
    }

    /**
     * @return array{warning:string, warning_link_href?:string, warning_link_label?:string, warning_copy_text?:string, warning_copy_label?:string}
     */
    public static function warning(
        string $message,
        string $linkHref = '',
        string $linkLabel = '查看',
        string $copyText = '',
        string $copyLabel = '复制',
    ): array {
        $message = (string) $message;
        $linkHref = trim((string) $linkHref);
        $linkLabel = trim((string) $linkLabel);
        $copyText = trim((string) $copyText);
        $copyLabel = trim((string) $copyLabel);

        $payload = [
            'warning' => $message,
        ];

        if ($linkHref !== '') {
            $payload['warning_link_href'] = $linkHref;
            $payload['warning_link_label'] = $linkLabel !== '' ? $linkLabel : '查看';
        }

        if ($copyText !== '') {
            $payload['warning_copy_text'] = $copyText;
            $payload['warning_copy_label'] = $copyLabel !== '' ? $copyLabel : '复制';
        }

        return $payload;
    }

    /**
     * 把 payload 批量 apply 到 redirect response（统一 session key 处理口径）。
     *
     * @param  object  $redirect  需提供 ->with($key,$value)
     */
    public static function apply(object $redirect, array $payload): object
    {
        $alwaysKeys = ['success', 'warning', 'error'];

        foreach ($payload as $k => $v) {
            $k = (string) $k;

            if (in_array($k, $alwaysKeys, true)) {
                $redirect = $redirect->with($k, $v);
                continue;
            }

            if ($v === null) {
                continue;
            }

            if (is_string($v)) {
                if (trim($v) === '') {
                    continue;
                }
                $redirect = $redirect->with($k, $v);
                continue;
            }

            $redirect = $redirect->with($k, $v);
        }

        return $redirect;
    }
}
