<?php

namespace routes;

use classes\authentication;
use objects\logs_o;
use objects\passkeys_o;
use traits\route_t;

class passkeysRoute
{
    use route_t;

    public function run(): void
    {
        // List passkeys for current authenticated user
        $this->get('/account/security/passkeys', function () {
            global $response;
            self::requirePermission('user_security_passkeys_list');
            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_LIST', 'User not logged in');
                $response->error('Invalid session', 400);
            }

            $passkeys = new passkeys_o();
            // Restrict to current user (customer) and non-subuser records
            $passkeys->setAdditionalWhereClause('WHERE user_id = ' . (int)$user->id . ' AND is_subuser = 0 AND deleted_at IS NULL');
            $list = $passkeys->listObjects(function ($o) {
                return [
                    'id' => $o->id,
                    'credential_id' => $o->credential_id->value(),
                    'name' => $o->name->value(),
                    'algorithm' => $o->algorithm->value(),
                    'transports' => $o->transports->value(),
                    'sign_count' => $o->sign_count->value(),
                    'created_at' => $o->created_at->value(),
                    'updated_at' => $o->updated_at->value(),
                ];
            });

            (new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_LIST', 'Listed passkeys');
            $response->success($list);
        }, [
            'user_security_passkeys_list' => 'List passkeys for the authenticated user',
        ]);

        // Create/add a passkey (store after client-side WebAuthn attestation)
        $this->post('/account/security/passkeys', function () {
            global $response;
            self::requirePermission('user_security_passkeys_create');
            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_CREATE', 'User not logged in');
                $response->error('Invalid session', 400);
            }

            self::requireParameters(['credential_id', 'public_key', 'algorithm', 'transports']);

            $credential_id = (string)self::getParameter('credential_id');
            self::requireType($credential_id, self::type_string());
            self::requireMinLength('credential_id', 16);
            self::requireMaxLength('credential_id', 4096);

            $public_key = (string)self::getParameter('public_key');
            self::requireType($public_key, self::type_string());
            self::requireMinLength('public_key', 32);
            self::requireMaxLength('public_key', 8192);

            $algorithm = (string)self::getParameter('algorithm');
            self::requireType($algorithm, self::type_string());
            self::requireMinLength('algorithm', 3);
            self::requireMaxLength('algorithm', 32);

            $transports = self::getParameter('transports');
            self::requireType($transports, self::TYPE_ARRAY());

            $name = self::getParameter('name');
            if ($name !== null) {
                $name = (string)$name;
                self::requireType($name, self::type_string());
                self::requireMinLength('name', 1);
                self::requireMaxLength('name', 255);
            }

            $obj = new passkeys_o();
            $obj->add((int)$user->id, false, $credential_id, $public_key, $algorithm, (array)$transports, $name);

            (new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_CREATE', 'Created passkey: ' . $obj->id);
            $response->success(['id' => $obj->id]);
        }, [
            'user_security_passkeys_create' => 'Create/add a new passkey for the authenticated user',
        ]);

        // Rename a passkey
        $this->patch('/account/security/passkeys/{id}', function () {
            global $response;
            self::requirePermission('user_security_passkeys_rename');
            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_RENAME', 'User not logged in');
                $response->error('Invalid session', 400);
            }

            $id = (int)self::fromRoute('id');
            self::requireParameterIntPositive($id, 'id');
            self::requireParameters(['name']);
            $name = (string)self::getParameter('name');
            self::requireType($name, self::type_string());
            self::requireMinLength('name', 1);
            self::requireMaxLength('name', 255);

            $obj = (new passkeys_o())->select($id);
            if (!$obj->exists() || (int)$obj->user_id->value() !== (int)$user->id || (int)$obj->is_subuser->value() !== 0) {
                (new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_PASSKEYS_RENAME', 'Passkey not found or not owned');
                $response->error('Not found', 404);
            }

            $obj->update(['name' => $name]);
            (new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_RENAME', 'Renamed passkey ' . $id);
            $response->success(['message' => 'Renamed', 'id' => $id]);
        }, [
            'user_security_passkeys_rename' => 'Rename a passkey that belongs to the authenticated user',
        ]);

        // Delete a passkey (soft delete)
        $this->delete('/account/security/passkeys/{id}', function () {
            global $response;
            self::requirePermission('user_security_passkeys_delete');
            $user = (new authentication())->get_user();
            if (!$user) {
                (new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_PASSKEYS_DELETE', 'User not logged in');
                $response->error('Invalid session', 400);
            }

            $id = (int)self::fromRoute('id');
            self::requireParameterIntPositive($id, 'id');

            $obj = (new passkeys_o())->select($id);
            if (!$obj->exists() || (int)$obj->user_id->value() !== (int)$user->id || (int)$obj->is_subuser->value() !== 0) {
                (new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_PASSKEYS_DELETE', 'Passkey not found or not owned');
                $response->error('Not found', 404);
            }

            $obj->delete();
            (new logs_o())->add('user_security', 'global', 1, $user->id, 'USER_SECURITY_PASSKEYS_DELETE', 'Deleted passkey ' . $id);
            $response->success(['message' => 'Deleted', 'id' => $id]);
        }, [
            'user_security_passkeys_delete' => 'Delete a passkey that belongs to the authenticated user',
        ]);
    }
}
