<?php
// app/controllers/logs.php

declare(strict_types=1);

use ScMedia\Http\Response;
use ScMedia\Http\Router;
use ScMedia\Services\LogService;
use ScMedia\Services\SettingsService;

final class LogsController extends BaseController {
  public static function register(Router $router, Container $container): void {
    $self = new self($container);
    $router->add('POST', '/api/logs', fn() => $self->listLogs());
    $router->add('POST', '/api/logs/cleanup', fn() => $self->cleanup());
  }

  private function listLogs(): void {
    /** @var LogService $logger */
    $logger = $this->logger();
    [$page, $perPage, $sort, $dir, $filters, $params] = table_body_params(100, 500);
    $from = (string)($params['from'] ?? '');
    $to = (string)($params['to'] ?? '');
    $level = (string)($params['level'] ?? '');

    if ($from === '' || $to === '') {
      $rangeValue = filter_value($filters, 'ts');
      $rangeOp = filter_op($filters, 'ts');
      if ($rangeOp === 'between' && is_array($rangeValue)) {
        $from = (string)($rangeValue[0] ?? '');
        $to = (string)($rangeValue[1] ?? '');
      }
    }
    if ($level === '') {
      $levelValue = filter_value($filters, 'level');
      if (is_string($levelValue)) {
        $level = $levelValue;
      }
    }

    if ($from === '' || $to === '') {
      Response::json(['ok' => true, 'data' => [
        'items' => [],
        'total' => 0,
        'page' => 1,
        'per_page' => $perPage,
      ]]);
      return;
    }

    $rows = $logger->listByRangePaged($from, $to, $page, $perPage, $level, $sort, $dir);
    Response::json(['ok' => true, 'data' => $rows]);
  }

  private function cleanup(): void {
    /** @var LogService $logger */
    $logger = $this->logger();
    /** @var SettingsService $settings */
    $settings = $this->settings();

    $body = read_json_body();
    $keep = isset($body['keep_days']) ? (int)$body['keep_days'] : null;
    if ($keep === null) {
      $all = $settings->getAll();
      $keep = (int)($all['logs']['retention_days'] ?? 7);
    }

    $deleted = $logger->cleanup($keep);
    $logger->log('info', 'Logs cleanup', ['keep_days' => $keep, 'deleted' => $deleted]);
    Response::json(['ok' => true, 'data' => ['deleted' => $deleted]]);
  }
}
