import { z } from 'zod';

export default class Network  {
    prefix = `NETWORK`
    indices = null

    constructor(indices) {
        this.indices = indices
    }

    schema = z.object({
        id: z.number(),
        name: z.string(),
        apps: z.array(z.string()),
        logo: z.string(),
        abbreviation: z.string(),
        created: z.string(),
        stripeAccountId: z.string().nullable(),
        stripeAccessToken: z.string().nullable()
    })
    .strict()

    get(id) {
        if(typeof id === "string") {
            id = id.split("-")[1]
        }
        let index = this.indices[0] + (id - 1)
        return structuredClone(global.db.nodes[index])
    }

    getByAbbreviation(abbreviation) {
        for(let i=this.indices[0]; i<this.indices[1]; i++) {
            if(global.db.nodes[i].abbreviation === abbreviation) {
                return global.db.nodes[i]
            }
        }
        return null
    }

    update(id, data) {
        if(data.id || data.created) {
            throw new Error("Can't update node id or created time!")
        }
        let currentObject = this.get(id)
        let newObject = {...currentObject, ...data}
        
        try {
            global.db.updateNode(this.prefix, newObject.id, newObject)
        } catch(e) {
            console.error(e)
            throw new global.ServerError(400, "Failed to add member!");
        }
    }

    save(n) {
        let id = `${this.prefix}-${n.id}`
        let result = this.schema.safeParse(n)
        if(result.success) {
            try {
                super.add(id, n)
            } catch(e) {
                console.error(e)
                throw e
            }
        } else {
            console.error(result.error)
            throw new global.ServerError(400, "Invalid Member Data!");
        }
    }

    add(n) {
        let toSave = {
            id: this.entries.length+1,
            ...n
        }
        this.save(toSave)
    }
}