<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Services\Payments\PaymentNotificationService;
use Illuminate\Console\Command;

class SendMonthlyPaymentNotificationsCommand extends Command
{
    protected $signature = 'payments:monthly-reminder {--force} {--email=} {--type=}';
    protected $description = 'Send monthly payment reminders on the first Saturday of every month.';

    public function handle(PaymentNotificationService $service): int
    {
        $force = (bool) $this->option('force');
        $email = (string) ($this->option('email') ?? '');
        $type = (string) ($this->option('type') ?? '');

        if ($email !== '') {
            $user = User::query()->where('email', $email)->first();
            if (!$user) {
                $this->error('Invalid --email provided.');
                return self::FAILURE;
            }

            $result = $service->send([
                'parent_id' => (int) $user->id,
                'type' => $type,
                'force' => true,
            ]);

            $this->info('Test reminder sent for ' . $email . '.');
            return $result['failed'] > 0 ? self::FAILURE : self::SUCCESS;
        }

        if (!$force && !$this->isFirstSaturday(now())) {
            $this->info('Not the first Saturday of the month. Use --force to override.');
            return self::SUCCESS;
        }

        $result = $service->send([
            'type' => $type,
            'force' => $force,
        ]);

        $this->info(sprintf('Done. Sent: %d, Skipped: %d, Failed: %d.', $result['sent'], $result['skipped'], $result['failed']));

        return $result['failed'] > 0 ? self::FAILURE : self::SUCCESS;
    }

    private function isFirstSaturday(\DateTimeInterface $dt): bool
    {
        return (int) $dt->format('w') === 6 && (int) $dt->format('j') <= 7;
    }
}
