/**
 * @file hsm-signer.ts
 * @notice HSM-backed signer for bridge operations
 */

import { ethers } from 'ethers';
import { EIP712TypedData } from './types';

export interface HSMSignerConfig {
    hsmEndpoint: string;
    hsmApiKey: string;
    keyId: string;
}

export class HSMSigner {
    private config: HSMSignerConfig;
    private provider: ethers.Provider;

    constructor(config: HSMSignerConfig, provider: ethers.Provider) {
        this.config = config;
        this.provider = provider;
    }

    /**
     * Sign EIP-712 typed data using HSM
     */
    async signTypedData(typedData: EIP712TypedData): Promise<string> {
        try {
            const response = await fetch(`${this.config.hsmEndpoint}/sign`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.config.hsmApiKey}`
                },
                body: JSON.stringify({
                    keyId: this.config.keyId,
                    typedData
                })
            });

            if (!response.ok) {
                throw new Error(`HSM signing failed: ${response.statusText}`);
            }

            const result = await response.json();
            return result.signature;
        } catch (error: any) {
            throw new Error(`HSM signing error: ${error.message}`);
        }
    }

    /**
     * Sign raw message using HSM
     */
    async signMessage(message: string): Promise<string> {
        try {
            const response = await fetch(`${this.config.hsmEndpoint}/sign-message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.config.hsmApiKey}`
                },
                body: JSON.stringify({
                    keyId: this.config.keyId,
                    message
                })
            });

            if (!response.ok) {
                throw new Error(`HSM signing failed: ${response.statusText}`);
            }

            const result = await response.json();
            return result.signature;
        } catch (error: any) {
            throw new Error(`HSM signing error: ${error.message}`);
        }
    }

    /**
     * Get HSM public key
     */
    async getPublicKey(): Promise<string> {
        try {
            const response = await fetch(
                `${this.config.hsmEndpoint}/keys/${this.config.keyId}`,
                {
                    headers: {
                        'Authorization': `Bearer ${this.config.hsmApiKey}`
                    }
                }
            );

            if (!response.ok) {
                throw new Error(`Failed to get public key: ${response.statusText}`);
            }

            const result = await response.json();
            return result.publicKey;
        } catch (error: any) {
            throw new Error(`HSM error: ${error.message}`);
        }
    }

    /**
     * Verify HSM is accessible
     */
    async healthCheck(): Promise<boolean> {
        try {
            const response = await fetch(`${this.config.hsmEndpoint}/health`, {
                headers: {
                    'Authorization': `Bearer ${this.config.hsmApiKey}`
                }
            });

            return response.ok;
        } catch (error) {
            return false;
        }
    }
}
