<?php
/**
 * PasskeysTable - stored FIDO2 public-key credentials.
 *
 * @package UltraguardPro\modules\authenticator\db
 */

namespace UltraguardPro\modules\authenticator\db;

use UltraguardPro\db\BaseTable;

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

class PasskeysTable extends BaseTable {

    protected $table_name  = 'ultraguard_passkeys';
    protected $cache_group = 'ultraguard_passkeys';

    public function get_defaults(): array {
        return [
            'id'            => 0,
            'user_id'       => 0,
            'credential_id' => '',
            'public_key'    => '',
            'sign_count'    => 0,
            'aaguid'        => null,
            'device_name'   => '',
            'last_used'     => null,
            'created_at'    => '',
        ];
    }

    protected function validate_data( $data ) {
        if ( empty( $data['user_id'] ) || empty( $data['credential_id'] ) || empty( $data['public_key'] ) ) {
            return false;
        }

        return $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];

        foreach ( $data as $k => $v ) {
            switch ( $k ) {
                case 'user_id':
                case 'sign_count':
                    $out[ $k ] = absint( $v );
                    break;

                case 'public_key':
                    $out[ $k ] = (string) $v;
                    break;

                case 'credential_id':
                    $out[ $k ] = sanitize_text_field( (string) $v );
                    break;

                case 'aaguid':
                case 'last_used':
                    $out[ $k ] = null === $v ? null : sanitize_text_field( (string) $v );
                    break;

                default:
                    $out[ $k ] = is_string( $v ) ? sanitize_text_field( $v ) : $v;
                    break;
            }
        }

        return $out;
    }

    public function get_for_user( int $user_id ): array {
        return $this->get_by( [ 'user_id' => $user_id ], 50, 'created_at', 'DESC' );
    }

    public function get_by_credential_id( string $credential_id ): ?array {
        $results = $this->get_by( [ 'credential_id' => $credential_id ], 1 );

        return $results[0] ?? null;
    }

    public function update_sign_count( int $id, int $new_count ): bool {
        return $this->update( $id, [
            'sign_count' => $new_count,
            'last_used'  => gmdate( 'Y-m-d H:i:s' ),
        ] );
    }

    protected function get_searchable_fields(): array {
        return [ 'device_name', 'aaguid' ];
    }

    protected function invalidate_caches_after_insert() {
        $this->clear_all_caches();
    }

    protected function invalidate_caches_after_update( $id ) {
        $this->clear_all_caches();
    }

    protected function invalidate_caches_after_bulk() {
        $this->clear_all_caches();
    }
}
