<?php

namespace App\Mail\Workspace;

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

/**
 * Role-change email (Team Workspaces) — sent to a member when an owner/admin
 * changes their workspace role. Always-on alongside the in-app bell row;
 * ShouldQueue so the role-change request never blocks on SMTP. Model-free
 * scalar args (mirrors {@see ProjectAccessMail}).
 */
class WorkspaceRoleChangedMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public function __construct(
        public string $recipientName,
        public string $workspaceName,
        public string $role, // 'admin' | 'editor' | 'viewer'
        public string $actorName,
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: "Your role in \"{$this->workspaceName}\" changed",
        );
    }

    public function content(): Content
    {
        $siteName = self::settingString('site.name', (string) config('app.name', 'AppShot AI'));
        $supportEmail = self::settingString('site.support_email', (string) config('mail.from.address', ''));

        return new Content(
            markdown: 'mail.workspace.role-changed',
            with: [
                'siteName' => $siteName,
                'supportEmail' => $supportEmail,
                'recipientName' => $this->recipientName !== '' ? $this->recipientName : 'there',
                'workspaceName' => $this->workspaceName,
                'role' => ucfirst($this->role),
                'actorName' => $this->actorName !== '' ? $this->actorName : 'An admin',
            ],
        );
    }

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