<?php

namespace PortalPeople\invoicing\jobs;

use PortalPeople\invoicing\services\InvoiceGenerationService;
use Yii;
use yii\queue\JobInterface;

/**
 * Invoice Generation Job
 *
 * Async job to generate invoices for eligible orders.
 * Can be queued via Yii Queue for background processing.
 */
class InvoiceGenerationJob implements JobInterface
{
    /**
     * @var string|null Date to process (YYYY-MM-DD format)
     */
    public $date;

    /**
     * {@inheritdoc}
     */
    public function execute($queue)
    {
        $date = $this->date ?? date('Y-m-d');
        
        Yii::info(
            "Starting invoice generation job for date: {$date}",
            'NGauge_modules.surfinvoicing.job'
        );

        try {
            $service = new InvoiceGenerationService();
            $results = $service->generate($date, false);

            Yii::info(
                "Invoice generation completed: " . json_encode($results),
                'NGauge_modules.surfinvoicing.job'
            );

            if ($results['failed'] > 0) {
                Yii::warning(
                    "Invoice generation had failures: " . json_encode($results['errors']),
                    'NGauge_modules.surfinvoicing.job'
                );
            }

        } catch (\Exception $e) {
            Yii::error(
                "Invoice generation job failed: " . $e->getMessage(),
                'NGauge_modules.surfinvoicing.job'
            );
            throw $e;
        }
    }
}
