<?php

namespace App\Console\Commands;

use App\Models\Tenant;
use App\Services\TenantLifecycleNotificationService;
use Illuminate\Console\Command;

class SendTenantLifecycleReminders extends Command
{
    protected $signature = 'notifications:tenant-lifecycle-reminders {--dry-run : Show reminders without sending them}';

    protected $description = 'Send trial and overdue subscription reminders to tenants.';

    public function handle(TenantLifecycleNotificationService $notifications): int
    {
        $trialTenants = Tenant::query()
            ->onTrial()
            ->where(function ($query): void {
                $query->whereNull('trial_reminder_sent_at')
                    ->orWhere('trial_reminder_sent_at', '<=', now()->subDays(3));
            })
            ->orderBy('trial_ends_at')
            ->get();

        $overdueTenants = Tenant::query()
            ->expired()
            ->where('status', 'active')
            ->where(function ($query): void {
                $query->whereNull('overdue_reminder_sent_at')
                    ->orWhere('overdue_reminder_sent_at', '<=', now()->subWeek());
            })
            ->orderBy('subscription_ends_at')
            ->get();

        foreach ($trialTenants as $tenant) {
            $this->line('Trial reminder: '.$tenant->name);

            if (! $this->option('dry-run')) {
                $notifications->trialReminder($tenant);
                $tenant->update(['trial_reminder_sent_at' => now()]);
            }
        }

        foreach ($overdueTenants as $tenant) {
            $this->line('Overdue reminder: '.$tenant->name);

            if (! $this->option('dry-run')) {
                $notifications->overdueReminder($tenant);
                $tenant->update(['overdue_reminder_sent_at' => now()]);
            }
        }

        if ($trialTenants->isEmpty() && $overdueTenants->isEmpty()) {
            $this->info('No tenant lifecycle reminders are due.');
        }

        return self::SUCCESS;
    }
}
