<?php

namespace Fotogenic_AI;

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

/**
 * REST handler for Studio Page target list and summary.
 */
final class Rest_Studio_Page {
    private PageQueryAdapter $page_query_adapter;

    public function __construct( PageQueryAdapter $page_query_adapter ) {
        $this->page_query_adapter = $page_query_adapter;
    }

    public function register_routes( Rest_Router $router ): void {
        $router->register_route(
            'fotogenic-ai/v1',
            '/studio/pages',
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'handle_pages_list' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'q' => [
                        'type'    => 'string',
                        'default' => '',
                    ],
                    'page' => [
                        'type'    => 'integer',
                        'default' => 1,
                    ],
                    'perPage' => [
                        'type'    => 'integer',
                        'default' => 6,
                    ],
                ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/studio/page-summary',
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'handle_page_summary' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'id' => [
                        'type'    => 'integer',
                        'default' => 0,
                    ],
                    'pageId' => [
                        'type'    => 'integer',
                        'default' => 0,
                    ],
                ],
            ]
        );

    }

    public function handle_pages_list( \WP_REST_Request $request ) {
        if ( ! current_user_can( 'edit_pages' ) ) {
            return Messages::error( 'forbidden', 403 );
        }

        $q        = sanitize_text_field( (string) $request->get_param( 'q' ) );
        $q        = strlen( $q ) > 100 ? substr( $q, 0, 100 ) : $q;
        $page     = max( 1, absint( $request->get_param( 'page' ) ) );
        $per_page = absint( $request->get_param( 'perPage' ) );
        $per_page = $per_page <= 0 ? 6 : min( 50, max( 1, $per_page ) );

        $result      = $this->page_query_adapter->list_pages( $q, $page, $per_page );
        $items       = isset( $result['items'] ) && is_array( $result['items'] ) ? $result['items'] : [];
        $total_items = isset( $result['totalItems'] ) ? (int) $result['totalItems'] : 0;
        $total_pages = isset( $result['totalPages'] ) ? max( 1, (int) $result['totalPages'] ) : 1;

		return rest_ensure_response(
			$this->sanitize_for_json(
				[
					'items'      => $items,
					'page'       => $page,
					'perPage'    => $per_page,
					'totalPages' => $total_pages,
					'totalItems' => $total_items,
				]
			)
		);
    }

    public function handle_page_summary( \WP_REST_Request $request ) {
        if ( ! current_user_can( 'edit_pages' ) ) {
            return Messages::error( 'forbidden', 403 );
        }

        $id = $this->resolve_page_id( $request );
        if ( $id <= 0 ) {
            return Messages::error( 'invalid_request', 400 );
        }

        $summary = $this->page_query_adapter->get_page_summary( $id );
        if ( is_wp_error( $summary ) ) {
            $status = (int) ( $summary->get_error_data()['status'] ?? 403 );
            return Messages::error( 'forbidden', $status );
        }
        if ( null === $summary ) {
            return Messages::error( 'invalid_request', 404 );
        }

		return rest_ensure_response( $this->sanitize_for_json( $summary ) );
    }

    private function resolve_page_id( \WP_REST_Request $request ): int {
        $page_id = absint( $request->get_param( 'pageId' ) );
        if ( $page_id > 0 ) {
            return $page_id;
        }
        return absint( $request->get_param( 'id' ) );
    }

    private function sanitize_for_json( $payload ) {
        if ( is_array( $payload ) ) {
            $out = [];
            foreach ( $payload as $key => $value ) {
                $out[ $key ] = $this->sanitize_for_json( $value );
            }
            return $out;
        }
        if ( $payload instanceof \stdClass ) {
            return $this->sanitize_for_json( (array) $payload );
        }
        if ( is_object( $payload ) || is_resource( $payload ) ) {
            return '';
        }
        if ( is_string( $payload ) ) {
            return wp_check_invalid_utf8( $payload, true );
        }
        if ( is_int( $payload ) || is_float( $payload ) || is_bool( $payload ) || null === $payload ) {
            return $payload;
        }
        return $payload;
    }
}
