import OrderedObject from "./OrderedObject.js"
const { z } = require("zod")

export default class Tokens extends OrderedObject {

    schema = z.object({
        index: z.number(),
        url: z.string(),
        uuid: z.string().regex(
            /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
            "Invalid UUID"
        ),
        used: z.boolean(),
    })

    markUsed(uuid) {
        let token = this.get(uuid)
        token.used = true
        super.update(`TOKEN-${uuid}`, token)
    }

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

    get(uuid) {
        return this.entries[this.ids[`TOKEN-${uuid}`]]
    }
}