import { decryptWithKey, derivePasswordMaterial, encryptWithKey, zeroize } from './crypto';
import { loadFileKey, storeFileKey } from './session';

/**
 * Before submitting a password change while praxis encryption is on:
 * re-wrap halfA + kek secret with the new password key, then replace the
 * password field with the login verifier.
 */
export function initPraxisPasswordChange(formSelector = 'form'): void {
    const form = document.querySelector(formSelector) as HTMLFormElement | null;
    const passwordInput = document.getElementById('user_password') as HTMLInputElement | null;
    if (!form || !passwordInput) {
        return;
    }

    form.addEventListener('submit', async (event) => {
        if ((form as HTMLFormElement & { __praxisPwReady?: boolean }).__praxisPwReady) {
            return;
        }

        const newPassword = passwordInput.value;
        if (!newPassword) {
            return;
        }

        event.preventDefault();

        try {
            const statusRes = await fetch('/api/praxis/status', {
                headers: { Accept: 'application/json' },
                credentials: 'same-origin',
            });
            const status = await statusRes.json();
            // Only the key holder re-wraps praxis material; other staff change passwords normally.
            if (!status.enabled || !status.keyHolder) {
                (form as HTMLFormElement & { __praxisPwReady?: boolean }).__praxisPwReady = true;
                form.submit();
                return;
            }

            const fileKey = loadFileKey();
            if (!fileKey) {
                alert('Please sign in again before changing the password (session key missing).');
                return;
            }

            const materialRes = await fetch('/api/praxis/session-material', {
                headers: { Accept: 'application/json' },
                credentials: 'same-origin',
            });
            const material = await materialRes.json();
            if (!materialRes.ok || !material.enabled) {
                throw new Error('session_material_failed');
            }

            const halfA = decryptWithKey(fileKey, material.encryptedHalfA);
            const secretBytes = decryptWithKey(fileKey, material.encryptedKekSecret);
            const derived = await derivePasswordMaterial(newPassword);
            const encryptedHalfA = encryptWithKey(derived.fileKey, halfA);
            const encryptedKekSecret = encryptWithKey(derived.fileKey, secretBytes);

            const rewrapRes = await fetch('/api/praxis/rewrap-password', {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    encryptedHalfA,
                    encryptedKekSecret,
                    passwordSalt: derived.saltB64,
                }),
            });
            if (!rewrapRes.ok) {
                throw new Error('rewrap_failed');
            }

            storeFileKey(derived.fileKey);
            passwordInput.value = derived.loginVerifier;
            zeroize(halfA, secretBytes, fileKey, derived.fileKey);

            (form as HTMLFormElement & { __praxisPwReady?: boolean }).__praxisPwReady = true;
            form.submit();
        } catch (e) {
            console.error(e);
            alert('Password change failed for password encryption. Please try again.');
        }
    });
}
