<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use App\Core\Request;
use App\Core\Response;
use App\Core\Tenant;

class ApiController extends Controller
{
    public function health(Request $request): never
    {
        Response::json([
            'ok' => true,
            'service' => 'veltrix-pos',
            'timestamp' => date(DATE_ATOM),
        ]);
    }

    public function me(Request $request): never
    {
        Response::json([
            'user' => auth_user(),
            'tenant_id' => Tenant::companyId(),
        ]);
    }

    public function metrics(Request $request): never
    {
        $companyId = Tenant::companyId();

        if ($companyId === null) {
            Response::json(['error' => 'tenant_required'], 422);
        }

        $pdo = Database::connection();
        $stmt = $pdo->prepare('SELECT COUNT(*) AS total_ventas, COALESCE(SUM(total),0) AS monto_total FROM ventas WHERE empresa_id = :empresa_id AND estado <> "anulada"');
        $stmt->execute([':empresa_id' => $companyId]);

        Response::json([
            'company_id' => $companyId,
            'metrics' => $stmt->fetch() ?: [],
        ]);
    }
}
