<?php

namespace Fotogenic_AI;

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

final class Rest_Auth {
    public function register_routes( Rest_Router $router ): void {
        $router->register_route(
            'fotogenic-ai/v1',
            '/auth/start',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_auth_start' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
                'args'                => [
                    'source' => [
                        'type'    => 'string',
                        'default' => 'settings',
                    ],
                ],
            ]
        );

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

        $router->register_route(
            'fotogenic-ai/v1',
            '/auth/logout',
            [
                'methods'             => 'POST',
                'callback'            => [ $this, 'handle_auth_logout' ],
                'permission_callback' => [ $router, 'permissions_admin' ],
            ]
        );
    }

    public function handle_auth_start( \WP_REST_Request $request ) {
        $source = sanitize_key( (string) $request->get_param( 'source' ) );
        $result = Auth_Session::instance()->start_login( $source );

        if ( is_wp_error( $result ) ) {
            return $result;
        }

        return rest_ensure_response( $result );
    }

    public function handle_auth_status( \WP_REST_Request $request ) {
        return rest_ensure_response( Auth_Session::instance()->get_public_status() );
    }

    public function handle_auth_logout( \WP_REST_Request $request ) {
        $auth = Auth_Session::instance()->logout();
        if ( is_wp_error( $auth ) ) {
            return $auth;
        }

        return rest_ensure_response(
            [
                'status' => 'logged_out',
                'auth'   => $auth,
            ]
        );
    }
}
