<?php

namespace App\Mail\Admin;

use App\Services\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

/**
 * Base for admin operational notifications (new sub, refund, payment
 * failed, webhook errors, etc). Queueable + branded with site name so
 * inbox previews tell the admin which install fired.
 *
 * Concrete classes provide envelope() (subject) and content() (markdown
 * view + extra data); the dispatcher resolves recipient via
 * NotificationSettings::adminEmail().
 */
abstract class BaseAdminNotification extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    protected function commonData(): array
    {
        $siteName = self::settingString('site.name', (string) config('app.name', 'AppShot AI'));
        $adminDashboardUrl = self::safeRoute('admin.dashboard');

        return [
            'siteName' => $siteName,
            'adminDashboardUrl' => $adminDashboardUrl,
        ];
    }

    /** Subject prefix that flags admin operational emails in the inbox
     *  list — distinguishes "[AppShot] New subscription" from a regular
     *  customer-facing email. */
    protected function adminSubject(string $tail): string
    {
        $siteName = self::settingString('site.name', (string) config('app.name', 'AppShot AI'));

        return "[{$siteName}] {$tail}";
    }

    private static function settingString(string $key, string $default): string
    {
        try {
            $value = Settings::get($key, $default);

            return is_string($value) && $value !== '' ? $value : $default;
        } catch (\Throwable) {
            return $default;
        }
    }

    private static function safeRoute(string $name): string
    {
        try {
            return route($name);
        } catch (\Throwable) {
            return rtrim((string) config('app.url'), '/').'/admin';
        }
    }
}
