<?php
/**
 * /backreload/v1/logs
 *
 * @package Backreload\Api
 */

namespace Backreload\Api;

use WP_REST_Request;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class LogsController extends BaseController {

	public function register( string $namespace ): void {
		register_rest_route( $namespace, '/logs', [
			[ 'methods' => 'GET',    'callback' => [ $this, 'index' ], 'permission_callback' => [ $this, 'check_perm' ] ],
			[ 'methods' => 'DELETE', 'callback' => [ $this, 'clear' ], 'permission_callback' => [ $this, 'check_perm' ] ],
		] );
	}

	public function index( WP_REST_Request $req ) {
		$items = $this->plugin->get( 'logger' )->fetch( [
			'level'     => (string) $req->get_param( 'level' ) ?: 'all',
			'search'    => (string) $req->get_param( 'search' ) ?: '',
			'backup_id' => (string) $req->get_param( 'backup_id' ) ?: '',
			'limit'     => (int) $req->get_param( 'limit' ) ?: 200,
			'offset'    => (int) $req->get_param( 'offset' ) ?: 0,
		] );
		return $this->ok( [ 'items' => $items ] );
	}

	public function clear() {
		$this->plugin->get( 'logger' )->truncate();
		return $this->ok( [ 'cleared' => true ] );
	}
}
