<?php
// app/controllers/items.php

declare(strict_types=1);

use ScMedia\Http\Router;
use ScMedia\Services\JobsService;
use ScMedia\Services\ScannerService;

final class ItemsController extends BaseController {
  public static function register(Router $router, Container $container): void {
    $self = new self($container);
    $router->add('GET', '/api/items', fn() => $self->listItems());
    $router->add('POST', '/api/items/scan', fn() => $self->scanItems());
  }

  private function listItems(): void {
    $db = $this->db();
    $status = $_GET['status'] ?? '';

    $where = [];
    $params = [];

    if ($status !== '') {
      $where[] = 'i.status = :status';
      $params[':status'] = $status;
    }

    $sql = "
      SELECT
        i.id,
        i.scan_profile_id,
        i.abs_path,
        i.rel_path,
        i.display_name,
        i.kind,
        i.year,
        i.structure,
        i.confidence,
        i.video_count,
        i.file_count,
        i.status,
        i.last_seen_at
      FROM items i
    ";

    if (count($where) > 0) {
      $sql .= " WHERE " . implode(' AND ', $where);
    }

    $sql .= " ORDER BY i.updated_at DESC, i.id DESC LIMIT 2000";

    $st = $db->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll();

    $items = [];
    foreach ($rows as $r) {
      $items[] = [
        'id' => (int)$r['id'],
        'scan_profile_id' => (int)$r['scan_profile_id'],
        'abs_path' => $r['abs_path'],
        'rel_path' => $r['rel_path'],
        'display_name' => $r['display_name'],
        'kind' => $r['kind'],
        'year' => $r['year'] !== null ? (int)$r['year'] : null,
        'structure' => $r['structure'],
        'confidence' => (int)$r['confidence'],
        'video_count' => (int)$r['video_count'],
        'file_count' => (int)$r['file_count'],
        'status' => $r['status'],
        'last_seen_at' => $r['last_seen_at'],
      ];
    }

    json_response(['ok' => true, 'items' => $items]);
  }

  private function scanItems(): void {
    /** @var JobsService $jobs */
    $jobs = $this->services()['jobs'];
    /** @var ScannerService $scanner */
    $scanner = $this->services()['scanner'];
    $logger = $this->logger();
    $settings = $this->settings();

    $bg = $settings->getAll()['background'] ?? [];
    if (!empty($bg['paused'])) {
      json_response(['ok' => false, 'error' => 'Background jobs paused'], 409);
    }

    $jobId = $jobs->create('scan', 'Scan (UI)', ['source' => 'http']);
    try {
      $jobs->start($jobId);
      $logger->log('info', 'Scan started', ['job_id' => $jobId, 'source' => 'http']);
      $result = $scanner->runScanJob($jobId);
      $status = $jobs->getStatus($jobId);
      if ($status !== 'canceled') {
        $jobs->finish($jobId);
        $logger->log('info', 'Scan finished', ['job_id' => $jobId, 'result' => $result]);
      } else {
        $logger->log('warn', 'Scan canceled', ['job_id' => $jobId]);
      }
      json_response(['ok' => true, 'job_id' => $jobId, 'result' => $result, 'status' => $status]);
    } catch (Throwable $e) {
      $jobs->log($jobId, 'error', $e->getMessage());
      $jobs->fail($jobId, $e->getMessage());
      $logger->log('error', 'Scan failed', ['job_id' => $jobId, 'error' => $e->getMessage()]);
      json_response(['ok' => false, 'error' => $e->getMessage()], 500);
    }
  }
}
