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

/**
 * Project activity email (Team Workspaces) — sent to the workspace OWNER when
 * an admin/editor creates (`kind = 'created'`) or deletes (`kind = 'deleted'`)
 * a project in their workspace. Always-on alongside the in-app bell row;
 * ShouldQueue so the create/delete request never blocks on SMTP. Model-free
 * scalar args (mirrors {@see ProjectAccessMail}).
 */
class ProjectActivityMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public function __construct(
        public string $recipientName,
        public string $projectName,
        public string $actorName,
        public string $kind, // 'created' | 'deleted'
        public ?string $openUrl = null,
    ) {}

    public function envelope(): Envelope
    {
        $subject = $this->kind === 'deleted'
            ? "{$this->actorName} deleted \"{$this->projectName}\""
            : "{$this->actorName} created \"{$this->projectName}\"";

        return new Envelope(subject: $subject);
    }

    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.project-activity',
            with: [
                'siteName' => $siteName,
                'supportEmail' => $supportEmail,
                'recipientName' => $this->recipientName !== '' ? $this->recipientName : 'there',
                'projectName' => $this->projectName,
                'actorName' => $this->actorName,
                'kind' => $this->kind,
                'openUrl' => $this->openUrl,
            ],
        );
    }

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