<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

class VerifyProfileEmailMailable extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    // /**
    //  * The name of the queue the job should be sent to.
    //  *
    //  * @var string
    //  */
    // public $queue = 'high';

    protected $notifiable;
    protected $verificationUrl;
    public $locale;

    /**
     * Create a new message instance.
     *
     * @param mixed $notifiable The user/profile that needs email verification
     * @return void
     */
    public function __construct($notifiable)
    {
        $this->notifiable = $notifiable;

        // Set the queue for this mailable
        $this->onQueue(queue: 'high');

        Log::info('VerifyProfileEmailMailable: Constructor called', [
            'notifiable_id' => $notifiable->id,
            'notifiable_type' => get_class($notifiable),
            'notifiable_lang_preference' => $notifiable->lang_preference ?? 'not set',
            'email' => $notifiable->email,
        ]);

        // Support lang_preference for User, Organization, Bank, and Admin models
        $this->locale = $notifiable->lang_preference ?? config('app.fallback_locale');

        // Ensure locale is not empty
        if (empty($this->locale)) {
            $this->locale = config('app.fallback_locale');
        }

        Log::info('VerifyProfileEmailMailable: Locale determined', [
            'locale' => $this->locale,
        ]);

        // Generate the verification URL
        $this->verificationUrl = $this->generateVerificationUrl($notifiable);

        Log::info('VerifyProfileEmailMailable: Verification URL generated', [
            'url' => $this->verificationUrl,
        ]);
    }

    /**
     * Generate the verification URL for the notifiable entity.
     *
     * @param mixed $notifiable
     * @return string
     */
    protected function generateVerificationUrl($notifiable)
    {
        $baseName = class_basename($notifiable);         // e.g. "User", "Organization"
        $type = Str::lower($baseName);

        // Generate a temporary signed route that expires in 60 minutes
        // Note: This route is intentionally NOT localized as it's defined
        // without locale prefix to work for users who are not yet logged in
        $signedUrl = URL::temporarySignedRoute(
            'verification.verify',
            Carbon::now()->addMinutes(60),
            [
                'type' => $type,
                'id' => $notifiable->id,
                'hash' => sha1($notifiable->getEmailForVerification()),
            ]
        );

        return $signedUrl;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // Set application locale for this email
        app()->setLocale($this->locale);

        $subject = trans('messages.verify_email_subject', [], $this->locale);
        $template = 'emails.verification.verify-email';

        Log::info('VerifyProfileEmailMailable: Building email', [
            'subject' => $subject,
            'template' => $template,
            'locale' => $this->locale,
            'from_email' => timebank_config('mail.support.email'),
            'from_name' => timebank_config('mail.support.name'),
        ]);

        return $this
            ->from(timebank_config('mail.support.email'), timebank_config('mail.support.name'))
            ->subject($subject)
            ->view($template)
            ->with([
                'notifiable' => $this->notifiable,
                'verificationUrl' => $this->verificationUrl,
            ]);
    }
}
