import type { Static } from "@sinclair/typebox"
import type { Document } from "mongoose"
import { Type } from "@sinclair/typebox"
import type { PluginFastifyInstance } from "types"

/**
 * Account Schema
 */
export const accountSchema = Type.Object(
  {
    _id: Type.String(),
    name: Type.String({ maxLength: 200 }),
    active: Type.Boolean({ default: true }),
    blocked: Type.Boolean({ default: false }),
    expires: Type.Optional(
      Type.Union([Type.String({ format: "date-time" }), Type.Null()]),
    ),
    owner: Type.Optional(Type.String({ default: null })),
    tags: Type.Array(Type.String(), { default: [] }),
    isDeleted: Type.Boolean({ default: false }),
    createdAt: Type.String({ format: "date-time" }),
    updatedAt: Type.String({ format: "date-time" }),
  },
  {
    $id: "#account/base",
    title: "core/account",
  },
)

/**
 * Type Utilities
 */

type DateTimeFields = {
  createdAt: Date
  updatedAt: Date
}

type RawAccount = Static<typeof accountSchema>

export type Account = Omit<RawAccount, keyof DateTimeFields> & DateTimeFields
export interface AccountDoc extends Document, Account {
  _id: string
}

export type AnyAccount = Account | AccountDoc

export { accountSchema as default }

/**
 * Register Schema/Type Generation for Shared Folder
 */
export const registerSchemas = (fastify: PluginFastifyInstance) => {
  fastify.registerSchema({
    schema: accountSchema,
    name: "Account",
  })
}
