import { prismaClient } from '../database/prismaClient.js';
import { isChainType } from '../utils/typeChecks.js';
export async function getAccount(id) {
    return prismaClient.account.findUnique({
        where: { id },
    });
}
export async function getAccountByAddress(address, chainType) {
    const parsedChainType = chainType.toLowerCase();
    if (!isChainType(parsedChainType)) {
        throw new Error(`Invalid chain type: ${chainType}`);
    }
    const addressRecord = await prismaClient.address.findUnique({
        where: { address, chainType: parsedChainType },
        include: { account: true },
    });
    return addressRecord?.account || null;
}
export async function listAccounts(limit = 50, offset = 0) {
    return prismaClient.account.findMany({
        take: limit,
        skip: offset,
    });
}
export async function createAccount(address, chainType) {
    let returnValue;
    const parsedChainType = chainType.toLowerCase();
    if (!isChainType(parsedChainType)) {
        throw new Error(`Invalid chain type: ${chainType}`);
    }
    const existingAddress = await prismaClient.address.findUnique({
        where: { address_chainType: { address, chainType: parsedChainType } },
    });
    // If the address already exists, so does the account
    if (existingAddress) {
        const account = await prismaClient.account.findUnique({
            where: { id: existingAddress.accountId },
            include: { addresses: true },
        });
        if (!account) {
            throw new Error(`Address "${existingAddress.address}" already exists but corresponding account "${existingAddress.accountId}" was not found.`);
        }
        returnValue = {
            account: account,
            addresses: account.addresses,
        };
    }
    else {
        const newAccount = await prismaClient.account.create({
            data: {
                addresses: {
                    create: {
                        address,
                        chainType: parsedChainType,
                    },
                },
            },
            include: { addresses: true },
        });
        returnValue = { addresses: newAccount.addresses, account: newAccount };
    }
    // Track connections
    prismaClient.connection.createMany({
        data: returnValue.addresses.map((address) => ({
            address: address.address,
            chain: address.chainType,
        })),
    });
    return returnValue;
}
export async function updateAccount(account) {
    const accountWithoutId = account;
    return prismaClient.account.update({
        where: { id: account.id },
        data: accountWithoutId,
    });
}
