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

namespace Backreload\Api;

use WP_REST_Request;

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

class ScheduleController extends BaseController {

	public function register( string $namespace ): void {
		register_rest_route( $namespace, '/schedules', [
			[ 'methods' => 'GET',  'callback' => [ $this, 'index' ],  'permission_callback' => [ $this, 'check_perm' ] ],
			[ 'methods' => 'POST', 'callback' => [ $this, 'create' ], 'permission_callback' => [ $this, 'check_perm' ] ],
		] );

		register_rest_route( $namespace, '/schedules/(?P<id>[a-zA-Z0-9_-]+)', [
			[ 'methods' => 'PATCH',  'callback' => [ $this, 'update' ],  'permission_callback' => [ $this, 'check_perm' ] ],
			[ 'methods' => 'DELETE', 'callback' => [ $this, 'destroy' ], 'permission_callback' => [ $this, 'check_perm' ] ],
		] );

		// Manual nuke of every queued backreload_* cron event — escape hatch
		// for the "no schedules but a backup keeps firing" loop after a
		// restore replays a stale cron table.
		register_rest_route( $namespace, '/schedules/purge-cron', [
			'methods'             => 'POST',
			'callback'            => [ $this, 'purge_cron' ],
			'permission_callback' => [ $this, 'check_perm' ],
		] );
	}

	public function purge_cron() {
		$removed = $this->plugin->get( 'scheduler' )->purge_all_scheduled_events();
		$this->plugin->get( 'logger' )->info( "Manual cron purge: removed {$removed} stale scheduled-backup event(s)" );
		return $this->ok( [ 'removed' => $removed ] );
	}

	public function index() {
		$sch  = $this->plugin->get( 'scheduler' );
		$next = $sch->combined_preview( 5 );
		return $this->ok( [ 'items' => $sch->all(), 'next' => $next ] );
	}

	public function create( WP_REST_Request $req ) {
		$sch = $this->plugin->get( 'scheduler' );
		$item = $sch->normalize( (array) $req->get_json_params() );
		$list = $sch->all();
		$list[] = $item;
		$sch->save_all( $list );
		return $this->ok( $item, 201 );
	}

	public function update( WP_REST_Request $req ) {
		$sch  = $this->plugin->get( 'scheduler' );
		$id   = (string) $req['id'];
		$list = $sch->all();
		foreach ( $list as &$s ) {
			if ( ( $s['id'] ?? null ) !== $id ) continue;
			$s = $sch->normalize( array_merge( $s, (array) $req->get_json_params() ), $id );
			$sch->save_all( $list );
			return $this->ok( $s );
		}
		return $this->error( 'not_found', 'Schedule not found', 404 );
	}

	public function destroy( WP_REST_Request $req ) {
		$sch  = $this->plugin->get( 'scheduler' );
		$id   = (string) $req['id'];
		$list = $sch->all();
		$next = array_values( array_filter( $list, fn( $s ) => ( $s['id'] ?? null ) !== $id ) );
		if ( count( $next ) === count( $list ) ) {
			return $this->error( 'not_found', 'Schedule not found', 404 );
		}
		$sch->save_all( $next );
		return $this->ok( [ 'deleted' => true ] );
	}
}
