<?php

namespace Planaday\Utility\Debug\Log;

use Planaday\Platform\PlatformAbstraction\UserService;
use Planaday\Utility\Endpoints\ApiController;
use Planaday\Utility\Endpoints\ApiEndpoint;
use Planaday\Utility\Endpoints\RequestData;

#[ApiController(1, "log")]
class ErrorLogFileReader {
	protected array $files = [];

	public function __construct(
		protected UserService $userService
	) {
		$this->indexFiles();
	}

	protected function indexFiles(): void {
		$logDir = dirname( __DIR__, 5 ) . "/assets/logs";
		$output = [];

		if(is_dir($logDir) === false) return;

		$years = scandir($logDir);
		foreach($years as $year) {
			$yearDir = $logDir . '/' . $year;
			if(is_dir($yearDir) === false) continue;

			$months = scandir($yearDir);
			foreach($months as $month) {
				$monthDir = $yearDir . '/' . $month;
				if(is_dir($monthDir) === false) continue;

				$logs = scandir($monthDir);
				foreach($logs as $log) {
					$valid = preg_match("@^$year-$month-([0-3][0-9])\.log$@", $log, $matches, PREG_UNMATCHED_AS_NULL);

					if (!$valid) {
						continue;
					}

					$output[$year] ??= [];
					$output[$year][$month] ??= [];
					$output[$year][$month][] = $matches[1];
				}
			}
		}

		$this->files = $output;
	}

	#[ApiEndpoint("getAll")]
	public function getFiles(): array {
		return $this->files;
	}

	#[ApiEndpoint("get/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)")]
	public function getLogEndpoint(RequestData $request): array {
		if (!$this->userService->isAdmin())
			return ["403"];

		return $this->getFileContents($request->getUrlParams()['year'], $request->getUrlParams()['month'], $request->getUrlParams()['day']);
	}

	public function getFileContents(string $year, string $month, string $day): array {
		$file = file_get_contents(dirname( __DIR__, 5 ) . "/assets/logs/$year/$month/$year-$month-$day.log");
		$lines = explode("\n", $file);

		$logs = [];
		foreach($lines as $line) {
			$logs[] = json_decode($line, true);
		}
		return $logs;
	}
}