<?php

namespace Hexspoor\MonitorClient\Console\Commands;

use Hexspoor\MonitorClient\Contracts\ClientContract;
use Hexspoor\MonitorClient\Models\MonitorLog;
use Illuminate\Console\Command;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use function logger;

class SendLogsToMonitorCommand extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'monitor:export';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export pending logs to monitor';

    public function handle(ClientContract $client): void
    {
        $progress = $this->output->createProgressBar();

        $progress->setMaxSteps(3);

        $logs = MonitorLog::query()
            ->select([
                'monitor_logs.*',
                'monitor_logs.created_at as logged_at',
            ])
            ->selectRaw('? AS reporting_system_id', [$client->getSystemId()])
            ->selectRaw('IF(system_id IS NOT NULL,system_id,?) AS system_id', [$client->getSystemId()])
            ->get();

        logger("{$logs->count()} log(s) to export");
        $progress->advance();

        if ($logs->isNotEmpty()) {
            $logs->chunk(30)->each(function (Collection $chunk) use ($client, $progress) {
                $response = $client->postLogs($chunk->toArray());

                logger("Server responded with: {$response->status()}");

                $progress->advance();

                if ($response->status() === Response::HTTP_OK) {
                    logger("Deleting logs");
                    $chunk->each(fn(MonitorLog $log) => $log->delete());
                }
            });
        }

        $progress->finish();
    }
}
