<?php

namespace App\Console\Commands;

use App\Services\ContractService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class ExpireContractsReport extends Command
{
    protected $signature = 'inoffice:expireContractsReport';

    protected $description = 'Send an email report of contracts that are expiring or have expired.';

    public function __construct(private ContractService $contractService)
    {
        parent::__construct();
    }

    public function handle(): int
    {
        $result  = $this->contractService->getExpireContracts();
        $expire  = $result['expire'];
        $expired = $result['expired'];

        $this->info("Expiring soon: " . count($expire));
        $this->info("Already expired: " . count($expired));

        if (empty($expire) && empty($expired)) {
            $this->info('No contracts expiring or expired. No email sent.');
            return self::SUCCESS;
        }

        $adminEmail = env('ADMIN_EMAIL');

        if (!$adminEmail) {
            $this->warn('No admin email configured (MAIL_ADMIN_ADDRESS). Email not sent.');
            $this->table(
                ['Customer', 'Contract No', 'Status'],
                array_merge(
                    array_map(fn($c) => [$c->customer_name, $c->contract_no, 'Expiring soon'], $expire),
                    array_map(fn($c) => [$c->customer_name, $c->contract_no, 'EXPIRED'], $expired),
                )
            );
            return self::SUCCESS;
        }

        try {
            Mail::send(
                'emails.expireContracts',
                ['expire' => $expire, 'expired' => $expired],
                fn($m) => $m->to($adminEmail)->subject('InOffice — Pregled isteka ugovora ' . now()->format('d.m.Y'))
            );

            $this->info("Report email sent to {$adminEmail}");
        } catch (\Throwable $e) {
            $this->error("Failed to send report email: " . $e->getMessage());
            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}
