<?php

/**
 * Settings Snapshot REST API Controller.
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use ProRank\SEO\Core\SettingsSnapshot;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

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


/**
 * Settings Snapshot controller class.
 */


class SettingsSnapshotController extends BaseController {
    
    /**
     * Settings Snapshot instance
     *
     * @var SettingsSnapshot
     */
    private SettingsSnapshot $snapshot_manager;
    
    /**
     * Constructor
     *
     * @param SettingsSnapshot $snapshot_manager Snapshot manager instance
     */
    public function __construct(SettingsSnapshot $snapshot_manager) {
        $this->snapshot_manager = $snapshot_manager;
    }
    
    /**
     * Register routes.
     *
     * @return void
     */
    public function register_routes(): void {
        // Get all snapshots
        register_rest_route(
            $this->namespace,
            '/settings/snapshots',
            [
                [
                    'methods'             => 'GET',
                    'callback'            => [$this, 'get_snapshots'],
                    'permission_callback' => [$this, 'check_admin_permission'],
                ],
                'schema' => [$this, 'get_snapshots_schema'],
            ]
        );
        
        // Create snapshot
        register_rest_route(
            $this->namespace,
            '/settings/snapshots',
            [
                [
                    'methods'             => 'POST',
                    'callback'            => [$this, 'create_snapshot'],
                    'permission_callback' => [$this, 'check_admin_permission'],
                    'args'                => [
                        'label' => [
                            'type'              => 'string',
                            'sanitize_callback' => 'sanitize_text_field',
                        ],
                    ],
                ],
            ]
        );
        
        // Revert to snapshot
        register_rest_route(
            $this->namespace,
            '/settings/snapshots/revert/(?P<snapshot_id>[a-zA-Z0-9_]+)',
            [
                [
                    'methods'             => 'POST',
                    'callback'            => [$this, 'revert_snapshot'],
                    'permission_callback' => [$this, 'check_admin_permission'],
                    'args'                => [
                        'snapshot_id' => [
                            'required'          => true,
                            'type'              => 'string',
                            'sanitize_callback' => 'sanitize_text_field',
                        ],
                    ],
                ],
            ]
        );
        
        // Delete snapshot
        register_rest_route(
            $this->namespace,
            '/settings/snapshots/(?P<snapshot_id>[a-zA-Z0-9_]+)',
            [
                [
                    'methods'             => 'DELETE',
                    'callback'            => [$this, 'delete_snapshot'],
                    'permission_callback' => [$this, 'check_admin_permission'],
                    'args'                => [
                        'snapshot_id' => [
                            'required'          => true,
                            'type'              => 'string',
                            'sanitize_callback' => 'sanitize_text_field',
                        ],
                    ],
                ],
            ]
        );
    }
    
    /**
     * Get all snapshots.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response object or error.
     */
    public function get_snapshots(WP_REST_Request $request) {
        try {
            $snapshots = $this->snapshot_manager->list_snapshots();
            
            // Format timestamps for display
            foreach ($snapshots as &$snapshot) {
                if (isset($snapshot['timestamp'])) {
                    $snapshot['formatted_date'] = wp_date(
                        get_option('date_format') . ' ' . get_option('time_format'),
                        $snapshot['timestamp']
                    );
                }
            }
            
            return $this->success_response([
                'snapshots' => array_values($snapshots),
                'total' => count($snapshots),
                'max_snapshots' => 10, // From SettingsSnapshot::MAX_SNAPSHOTS
            ]);
            
        } catch (\Exception $e) {
            return $this->error_response(
                __('Failed to fetch snapshots.', 'prorank-seo'),
                'fetch_failed',
                500
            );
        }
    }
    
    /**
     * Create a new snapshot.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response object or error.
     */
    public function create_snapshot(WP_REST_Request $request) {
        $label = $request->get_param('label');
        
        try {
            $snapshot_id = $this->snapshot_manager->create_snapshot($label);
            
            if (!$snapshot_id) {
                return $this->error_response(
                    __('Failed to create snapshot.', 'prorank-seo'),
                    'create_failed',
                    500
                );
            }
            
            return $this->success_response([
                'message' => __('Snapshot created successfully.', 'prorank-seo'),
                'snapshot_id' => $snapshot_id,
            ]);
            
        } catch (\Exception $e) {
            return $this->error_response(
                __('An error occurred while creating the snapshot.', 'prorank-seo'),
                'create_error',
                500
            );
        }
    }
    
    /**
     * Revert to a snapshot.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response object or error.
     */
    public function revert_snapshot(WP_REST_Request $request) {
        $snapshot_id = $request->get_param('snapshot_id');
        
        try {
            // Get snapshot details first
            $snapshot = $this->snapshot_manager->get_snapshot($snapshot_id);
            
            if (!$snapshot) {
                return $this->error_response(
                    __('Snapshot not found.', 'prorank-seo'),
                    'not_found',
                    404
                );
            }
            
            // Perform revert
            $success = $this->snapshot_manager->revert_to_snapshot($snapshot_id);
            
            if (!$success) {
                return $this->error_response(
                    __('Failed to revert to snapshot.', 'prorank-seo'),
                    'revert_failed',
                    500
                );
            }
            
            return $this->success_response([
                'message' => sprintf(
                    /* translators: %s: snapshot label */
                    __('Successfully reverted to "%1$s".', 'prorank-seo'),
                    $snapshot['label'] ?? __('Unknown snapshot', 'prorank-seo')
                ),
                'snapshot_id' => $snapshot_id,
            ]);
            
        } catch (\Exception $e) {
            return $this->error_response(
                __('An error occurred while reverting the snapshot.', 'prorank-seo'),
                'revert_error',
                500
            );
        }
    }
    
    /**
     * Delete a snapshot.
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error Response object or error.
     */
    public function delete_snapshot(WP_REST_Request $request) {
        $snapshot_id = $request->get_param('snapshot_id');
        
        try {
            $success = $this->snapshot_manager->delete_snapshot($snapshot_id);
            
            if (!$success) {
                return $this->error_response(
                    __('Failed to delete snapshot.', 'prorank-seo'),
                    'delete_failed',
                    500
                );
            }
            
            return $this->success_response([
                'message' => __('Snapshot deleted successfully.', 'prorank-seo'),
                'snapshot_id' => $snapshot_id,
            ]);
            
        } catch (\Exception $e) {
            return $this->error_response(
                __('An error occurred while deleting the snapshot.', 'prorank-seo'),
                'delete_error',
                500
            );
        }
    }
    
    /**
     * Check admin permission.
     *
     * @return bool True if user has permission.
     */
    public function check_admin_permission(): bool {
        return current_user_can('manage_options');
    }
    
    /**
     * Get snapshots schema.
     *
     * @return array Schema definition.
     */
    public function get_snapshots_schema(): array {
        return [
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'snapshots',
            'type'       => 'object',
            'properties' => [
                'snapshots' => [
                    'description' => __('List of settings snapshots.', 'prorank-seo'),
                    'type'        => 'array',
                    'items'       => [
                        'type'       => 'object',
                        'properties' => [
                            'id' => [
                                'description' => __('Snapshot ID.', 'prorank-seo'),
                                'type'        => 'string',
                            ],
                            'timestamp' => [
                                'description' => __('Creation timestamp.', 'prorank-seo'),
                                'type'        => 'integer',
                            ],
                            'formatted_date' => [
                                'description' => __('Formatted creation date.', 'prorank-seo'),
                                'type'        => 'string',
                            ],
                            'label' => [
                                'description' => __('Snapshot label.', 'prorank-seo'),
                                'type'        => 'string',
                            ],
                            'user_id' => [
                                'description' => __('Creator user ID.', 'prorank-seo'),
                                'type'        => 'integer',
                            ],
                            'user_name' => [
                                'description' => __('Creator display name.', 'prorank-seo'),
                                'type'        => 'string',
                            ],
                        ],
                    ],
                ],
                'total' => [
                    'description' => __('Total number of snapshots.', 'prorank-seo'),
                    'type'        => 'integer',
                ],
                'max_snapshots' => [
                    'description' => __('Maximum number of snapshots allowed.', 'prorank-seo'),
                    'type'        => 'integer',
                ],
            ],
        ];
    }
}