<?php

namespace App\Jobs;

use App\Models\Report\ManagementReportRecipient;
use App\Services\Dashboard\DailyManagementReportService;
use App\Services\SendGridEmailService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class SendDailyManagementReportJob implements ShouldBeUnique, ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 5;

    public int $timeout = 60;

    public int $uniqueFor = 90000;

    public array $backoff = [60, 300, 900, 3600, 14400];

    public function __construct(
        public int $recipientId,
        public string $cutoff,
    ) {}

    public function uniqueId(): string
    {
        return $this->recipientId.':'.Carbon::parse($this->cutoff)->toDateString();
    }

    public function handle(
        DailyManagementReportService $reports,
        SendGridEmailService $sendgrid,
    ): void {
        $recipient = ManagementReportRecipient::withoutGlobalScopes()
            ->find($this->recipientId);

        if (! $recipient || ! $recipient->is_active) {
            return;
        }

        $cutoff = Carbon::parse($this->cutoff, config('app.timezone'))
            ->timezone(config('app.timezone'));
        $reportDate = $cutoff->toDateString();

        if ($recipient->last_report_date?->toDateString() === $reportDate) {
            return;
        }

        $fromEmail = 'ab@deeplinx.ai';

        if (blank($fromEmail)) {
            throw new \RuntimeException('MAIL_FROM_ADDRESS is not configured for management reports.');
        }

        $report = $reports->build($cutoff);
        $html = view('emails.reports.daily-management', [
            'report' => $report,
        ])->render();

        $sendgrid->send([
            'to_email' => $recipient->email_address,
            'to_name' => $recipient->name ?? '',
            'from_email' => (string) $fromEmail,
            'from_name' => config('mail.from.name') ?: config('app.name'),
            'subject' => 'Daily Management Report (All Solicitors) - '.$cutoff->format('j F Y'),
            'html' => $html,
            'text' => $reports->text($report),
        ]);

        $recipient->forceFill([
            'last_report_date' => $reportDate,
            'last_sent_at' => now(),
        ])->save();
    }
}
