<?php
/**
 * Config REST Controller
 *
 * Handles post configuration operations.
 *
 * @package WP_Agentic_Writer
 */

/**
 * Class WP_Agentic_Writer_Controller_Config
 *
 * REST controller for post configuration operations.
 *
 * @since 0.3.0
 */
class WP_Agentic_Writer_Controller_Config {

    /**
     * Sidebar instance for dependency access.
     *
     * @var WP_Agentic_Writer_Gutenberg_Sidebar
     */
    private $sidebar;

    /**
     * Constructor.
     *
     * @since 0.3.0
     * @param WP_Agentic_Writer_Gutenberg_Sidebar $sidebar Sidebar instance.
     */
    public function __construct( $sidebar ) {
        $this->sidebar = $sidebar;
    }

    /**
     * Handle get post config request.
     *
     * @since 0.1.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error
     */
    public function handle_get_post_config( $request ) {
        $post_id = isset( $request['post_id'] ) ? (int) $request['post_id'] : 0;
        if ( $post_id <= 0 ) {
            return new WP_Error(
                'invalid_post',
                __( 'Invalid post ID.', 'wp-agentic-writer' ),
                [ 'status' => 400 ],
            );
        }

        if ( ! $this->sidebar->check_post_permission( $post_id ) ) {
            return new WP_Error(
                'forbidden',
                __(
                    'You do not have permission to access this post.',
                    'wp-agentic-writer',
                ),
                [ 'status' => 403 ],
            );
        }

        return new WP_REST_Response( $this->sidebar->get_post_config( $post_id ), 200 );
    }

    /**
     * Handle update post config request.
     *
     * @since 0.1.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error
     */
    public function handle_update_post_config( $request ) {
        $post_id = isset( $request['post_id'] ) ? (int) $request['post_id'] : 0;
        if ( $post_id <= 0 ) {
            return new WP_Error(
                'invalid_post',
                __( 'Invalid post ID.', 'wp-agentic-writer' ),
                [ 'status' => 400 ],
            );
        }

        if ( ! $this->sidebar->check_post_permission( $post_id ) ) {
            return new WP_Error(
                'forbidden',
                __(
                    'You do not have permission to edit this post.',
                    'wp-agentic-writer',
                ),
                [ 'status' => 403 ],
            );
        }

        $params = $request->get_json_params();
        $config = $this->sidebar->sanitize_post_config( $params['postConfig'] ?? [] );
        update_post_meta( $post_id, '_wpaw_post_config', $config );

        // MEMANTO: Store config preference.
        do_action( 'wpaw_memanto_config_saved', $post_id, $config );

        return new WP_REST_Response( $config, 200 );
    }
}
