<?php

namespace App\Services\Notifications;

use App\Models\EmailDeliveryLog;
use App\Models\ImportedJob;
use App\Models\JobAlertPreference;
use App\Models\User;
use App\Services\Email\TransactionalEmailSender;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\URL;

class DailyJobAlertMailer
{
    public function __construct(private readonly TransactionalEmailSender $emailSender) {}

    /**
     * @param  Collection<int, ImportedJob>  $jobs
     */
    /**
     * @param  array<string, mixed>  $extraMetadata
     */
    public function send(User $user, JobAlertPreference $preference, Collection $jobs, array $extraMetadata = []): EmailDeliveryLog
    {
        $unsubscribeUrl = URL::signedRoute('job-alerts.unsubscribe', [
            'preference' => $preference,
        ]);

        $subject = $jobs->count() === 1
            ? '1 new remote job matched your profile'
            : $jobs->count().' new remote jobs matched your profile';

        $html = view('emails.jobs.daily-alert', [
            'subject' => $subject,
            'preheader' => 'Fresh remote roles are ready in your RemoteMatch dashboard.',
            'jobs' => $jobs,
            'unsubscribeUrl' => $unsubscribeUrl,
        ])->render();

        return $this->emailSender->send(
            toEmail: $user->email,
            toName: $user->name,
            subject: $subject,
            html: $html,
            text: $this->text($jobs, $unsubscribeUrl),
            headers: [
                'List-Unsubscribe' => '<'.$unsubscribeUrl.'>',
                'List-Unsubscribe-Post' => 'List-Unsubscribe=One-Click',
            ],
            userId: $user->id,
            type: EmailDeliveryLog::TYPE_JOB_ALERT,
            metadata: array_replace([
                'job_alert_preference_id' => $preference->id,
                'imported_job_ids' => $jobs->pluck('id')->values()->all(),
                'unsubscribe_url' => $unsubscribeUrl,
            ], $extraMetadata),
            resendable: true,
        );
    }

    /**
     * @param  Collection<int, ImportedJob>  $jobs
     */
    private function text(Collection $jobs, string $unsubscribeUrl): string
    {
        $lines = [
            'Fresh remote jobs matched your profile:',
            '',
        ];

        foreach ($jobs as $job) {
            $lines[] = '- '.$job->title.($job->company ? ' at '.$job->company : '').': '.route('jobs.show', $job);
        }

        $lines[] = '';
        $lines[] = 'Open matched jobs: '.route('jobs.index');
        $lines[] = 'Unsubscribe from job alerts: '.$unsubscribeUrl;

        return implode("\n", $lines);
    }
}
