<?php

namespace Fotogenic_AI;

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

final class Rest_Admin {
    public function register_routes( Rest_Router $router ): void {
        $router->register_route(
            'fotogenic-ai/v1',
            '/settings/save',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_settings_save' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'settings' => [
                        'type'     => 'object',
                        'required' => true,
                    ],
                ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/settings/cache/refresh',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_settings_cache_refresh' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/notifications',
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'handle_notifications_list' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/notifications/upsert',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_notifications_upsert' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'event' => [
                        'type'     => 'object',
                        'required' => true,
                    ],
                ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/notifications/read',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_notifications_read' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/notifications/dismiss',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_notifications_dismiss' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/logs/list',
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'handle_logs_list' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'date_range' => [
                        'type' => 'string',
                        'enum' => [ 'today', '7d', '30d' ],
                    ],
                    'level'      => [
                        'type' => 'string',
                        'enum' => [ 'info', 'warning', 'error' ],
                    ],
                    'search'     => [
                        'type' => 'string',
                    ],
                    'page'       => [
                        'type'    => 'integer',
                        'minimum' => 1,
                        'default' => 1,
                    ],
                    'per_page'   => [
                        'type'    => 'integer',
                        'enum'    => [ 5, 10 ],
                        'default' => 5,
                    ],
                ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/logs/clear',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_logs_clear' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/logs/download',
            [
                'methods'             => 'GET',
                'callback'            => [ $this, 'handle_logs_download' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );

        $router->register_route(
            'fotogenic-ai/v1',
            '/logs/client-error',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_logs_client_error' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'error' => [
                        'type'     => 'object',
                        'required' => true,
                    ],
                    'context' => [
                        'type'    => 'object',
                        'default' => [],
                    ],
                ],
            ]
        );
    }

    public function handle_settings_save( \WP_REST_Request $request ) {
        $settings = $request->get_param( 'settings' );
        if ( ! is_array( $settings ) ) {
            return new \WP_Error( 'fotogenic_ai_invalid_settings', __( 'Invalid settings payload.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }

        $settings_service = Settings::instance();
        $existing = $settings_service->get_options();
        $sanitized = $settings_service->prepare_settings_for_save(
            $settings,
            [
                'context'  => 'rest',
                'existing' => $existing,
            ]
        );
        if ( is_wp_error( $sanitized ) ) {
            return $sanitized;
        }
        if ( ! is_array( $sanitized ) ) {
            return new \WP_Error( 'fotogenic_ai_invalid_settings', __( 'Could not save settings.', 'fotogenic-ai' ), [ 'status' => 500 ] );
        }

        update_option( $settings_service->get_option_name(), $sanitized, false );

        return rest_ensure_response( [
            'status'   => 'saved',
            'settings' => $sanitized,
            'auth'     => Auth_Session::instance()->get_public_status(),
        ] );
    }

    public function handle_settings_cache_refresh( \WP_REST_Request $request ) {
        return rest_ensure_response( Plugin_Cache_Refresher::instance()->refresh() );
    }

    public function handle_notifications_list( \WP_REST_Request $request ) {
        return rest_ensure_response( Notification_Activity_Store::instance()->list_for_user( get_current_user_id() ) );
    }

    public function handle_notifications_upsert( \WP_REST_Request $request ) {
        $event = $request->get_param( 'event' );
        if ( ! is_array( $event ) ) {
            return new \WP_Error( 'fotogenic_ai_notification_invalid', __( 'The notification activity was invalid.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }
        $result = Notification_Activity_Store::instance()->upsert_for_user( get_current_user_id(), $event );
        return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
    }

    public function handle_notifications_read( \WP_REST_Request $request ) {
        $ids = $request->get_param( 'ids' );
        $result = Notification_Activity_Store::instance()->mark_read_for_user(
            get_current_user_id(),
            is_array( $ids ) ? $ids : [],
            rest_sanitize_boolean( $request->get_param( 'all' ) )
        );
        return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
    }

    public function handle_notifications_dismiss( \WP_REST_Request $request ) {
        $result = Notification_Activity_Store::instance()->dismiss_for_user(
            get_current_user_id(),
            (string) $request->get_param( 'id' )
        );
        return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
    }

    public function handle_logs_list( \WP_REST_Request $request ) {
        $date_range = sanitize_key( (string) $request->get_param( 'date_range' ) );
        $level = sanitize_key( (string) $request->get_param( 'level' ) );
        $search = sanitize_text_field( (string) $request->get_param( 'search' ) );
        $page = max( 1, (int) $request->get_param( 'page' ) );
        $per_page = (int) $request->get_param( 'per_page' );
        if ( '' !== $date_range && ! in_array( $date_range, [ 'today', '7d', '30d' ], true ) ) {
            return new \WP_Error(
                'fotogenic_ai_invalid_log_date_range',
                __( 'Invalid log date range.', 'fotogenic-ai' ),
                [ 'status' => 400 ]
            );
        }
        if ( '' !== $level && ! in_array( $level, [ 'info', 'warning', 'error' ], true ) ) {
            return new \WP_Error(
                'fotogenic_ai_invalid_log_level',
                __( 'Invalid log level.', 'fotogenic-ai' ),
                [ 'status' => 400 ]
            );
        }
        if ( 0 === $per_page ) {
            $per_page = 5;
        }
        if ( ! in_array( $per_page, [ 5, 10 ], true ) ) {
            return new \WP_Error(
                'fotogenic_ai_invalid_log_page_size',
                __( 'Invalid log page size.', 'fotogenic-ai' ),
                [ 'status' => 400 ]
            );
        }

        $result = Logger::instance()->list_entries( $level, $search, $page, $per_page, $date_range );

        $date_format = get_option( 'date_format', 'Y-m-d' );
        $time_format = get_option( 'time_format', 'H:i:s' );
        $combined = $date_format . ' ' . $time_format;
        $entries = isset( $result['entries'] ) ? $result['entries'] : [];
        foreach ( $entries as $i => $entry ) {
            $ts = isset( $entry['timestamp'] ) ? $entry['timestamp'] : ( $entry['event_time'] ?? '' );
            if ( '' !== $ts ) {
                $ts_parsed = strtotime( $ts . ( false === strpos( $ts, 'T' ) ? ' UTC' : '' ) );
                $entries[ $i ]['formatted_timestamp'] = $ts_parsed ? wp_date( $combined, $ts_parsed ) : $ts;
            } else {
                $entries[ $i ]['formatted_timestamp'] = '';
            }
            $stored_level = strtolower( (string) ( $entry['level'] ?? '' ) );
            if ( in_array( $stored_level, [ 'api', 'info' ], true ) ) {
                $entries[ $i ]['level'] = 'INFO';
            } elseif ( 'warn' === $stored_level ) {
                $entries[ $i ]['level'] = 'WARNING';
            } elseif ( 'error' === $stored_level ) {
                $entries[ $i ]['level'] = 'ERROR';
            } else {
                $entries[ $i ]['level'] = '';
            }
        }
        $result['entries'] = $entries;

        return rest_ensure_response( $result );
    }

    public function handle_logs_clear( \WP_REST_Request $request ) {
        $deleted = Logger::instance()->delete_log_entries();
        update_option( 'fotogenic_ai_debug_logs_cleared_at', current_time( 'mysql', 1 ), false );
        return rest_ensure_response( [
            'status'  => 'cleared',
            'deleted' => $deleted,
        ] );
    }

    public function handle_logs_download( \WP_REST_Request $request ) {
        unset( $request );
        $logger = Logger::instance();
        $contents = $logger->export_entries_as_text();
        if ( '' === $contents ) {
            return Messages::error( 'missing_log', 404 );
        }
        $response = new \WP_REST_Response( $contents );
        $response->set_headers( [
            'Content-Type'        => 'text/plain; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="fotogenic-ai-logs.log"',
        ] );
        return $response;
    }

    public function handle_logs_client_error( \WP_REST_Request $request ) {
        $payload = $request->get_json_params();
        if ( ! is_array( $payload ) ) {
            $payload = [];
        }
        $error = isset( $payload['error'] ) && is_array( $payload['error'] ) ? $payload['error'] : $payload;
        $client_context = is_array( $payload['context'] ?? null ) ? $payload['context'] : [];
        Logger::instance()->support_error(
            sanitize_text_field( (string) ( $error['supportId'] ?? '' ) ),
            sanitize_key( (string) ( $error['errorCode'] ?? 'unknown_error' ) ),
            isset( $error['httpStatus'] ) ? (int) $error['httpStatus'] : 0,
            sanitize_key( (string) ( $client_context['step'] ?? '' ) )
        );
        return rest_ensure_response( [ 'ok' => true ] );
    }

}
