<?php

namespace App\Console\Commands;

use App\Master\InvoiceGenerator;
use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Tenant;

class GenerateInvoices extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoices:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate due invoices for clients/tenants';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(private InvoiceGenerator $generator)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Tenant::query()
            ->with([
                'billables.billable',
                'billingDetails',
            ])
            ->invoiceDue()
            ->get()
            ->each(fn (Tenant $tenant) => $tenant->checkBillingChange() && $this->generator->create($tenant));

        return 0;
    }
}
