<?php

namespace App\Mail;

use App\Models\Call;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CallExpiredMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $call;
    public $callable;
    public string $callableType;
    public string $mailLocale;
    public string $loginUrl;
    public string $callTitle;

    public function __construct(Call $call, $callable, string $callableType)
    {
        $this->call         = $call;
        $this->callable     = $callable;
        $this->callableType = $callableType;

        $this->mailLocale = $callable->lang_preference ?? config('app.fallback_locale', 'en');
        $this->locale($this->mailLocale);
        // callTitle is resolved in build() after locale is set
        $this->callTitle = $call->tag?->name ?? '';

        $callsRoute = LaravelLocalization::getURLFromRouteNameTranslated($this->mailLocale, 'routes.calls.manage');

        $base = match ($callableType) {
            'Organization' => route('organization.direct-login', ['organizationId' => $callable->id, 'intended' => $callsRoute]),
            'Bank'         => route('bank.direct-login',         ['bankId'         => $callable->id, 'intended' => $callsRoute]),
            default        => route('user.direct-login',         ['userId'         => $callable->id, 'intended' => $callsRoute]),
        };

        $this->loginUrl = LaravelLocalization::localizeURL($base, $this->mailLocale);
    }

    public function build()
    {
        app()->setLocale($this->mailLocale);

        $callTitle = $this->call->tag?->translation?->name ?? $this->call->tag?->name ?? '';

        return $this
            ->from(
                timebank_config('mail.system_admin.email'),
                timebank_config('mail.system_admin.name')
            )
            ->subject(trans('Your call has expired', [], $this->mailLocale))
            ->view('emails.calls.expired')
            ->with([
                'callable'  => $this->callable,
                'call'      => $this->call,
                'callTitle' => $callTitle,
                'loginUrl'  => $this->loginUrl,
            ]);
    }
}
