import { useDatabase } from "@/app/providers/DatabaseProvider/useDatabase";
import { createContext } from "react";
import { useSystemAccount } from "./useSystemAccount";
import { usePublicKey } from "../AccountProvider/usePublicKey";
import { usePrivatePlain } from "../AccountProvider/usePrivatePlain";
import { chacha20Encrypt, encodeWithPassword, encrypt } from "@/app/workers/crypto/crypto";
import { generateRandomKey } from "@/app/utils/utils";
import { DeliveredMessageState } from "../DialogProvider/DialogProvider";
import { UserInformation } from "../InformationProvider/InformationProvider";
import { useNotification } from "@/app/hooks/useNotification";
import { useDialogsList } from "../DialogListProvider/useDialogsList";

export interface SystemAccountContextValue {
    sendMessageFromSystemAccount: (accountUsername: string, message: string) => Promise<void>;
}

export const SystemAccountContext = createContext<SystemAccountContextValue | null>(null);

export interface SystemUserInformation extends UserInformation {
    avatar: string;
}

interface SystemAccountProviderProps {
    children: React.ReactNode;
}

export function SystemAccountProvider(props : SystemAccountProviderProps) {
    const {runQuery} = useDatabase();
    const publicKey = usePublicKey();
    const privatePlain = usePrivatePlain();
    const {updateDialog} = useDialogsList();
    const notify = useNotification();

    const sendMessageFromSystemAccount = async (accountUsername: string, message: string) => {
        const account = useSystemAccount(accountUsername);
        if(!account){
            throw new Error("System account not found");
        }
        const chachaEncrypted : any = await chacha20Encrypt(message.trim());
        const key = Buffer.concat([
            Buffer.from(chachaEncrypted.key, "hex"),
            Buffer.from(chachaEncrypted.nonce, "hex")]);
        const encryptedKey = await encrypt(key.toString('binary'), publicKey);
        const messageId = generateRandomKey(16);
        const plainMessage = await encodeWithPassword(privatePlain, message.trim());

        await runQuery(`
            INSERT INTO messages 
                (from_public_key, to_public_key, content, timestamp, read, chacha_key, from_me, plain_message, account, message_id, delivered, attachments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `, [account.publicKey, publicKey, chachaEncrypted.ciphertext, Date.now(), 0, encryptedKey, 0, plainMessage, publicKey, messageId, DeliveredMessageState.DELIVERED, JSON.stringify([])]);
        updateDialog(account.publicKey);
        notify("New message", "You have a new message");
    }


    return (
        <SystemAccountContext.Provider value={{
            sendMessageFromSystemAccount
        }}>
            {props.children}
        </SystemAccountContext.Provider>
    )
}