import type { Static } from "@sinclair/typebox"
import type { Document } from "mongoose"
import { Type } from "@sinclair/typebox"
import { PluginFastifyInstance } from "types"
/**
 * Base Project Schema - Fields common to all operations
 */
const projectConfigSchema = Type.Optional(
  Type.Object(
    {
      tags: Type.Array(Type.String(), { default: [] }),
      railPageNavigation: Type.Boolean({ default: false }),
    },
    {
      $id: "#project/config",
      title: "core/project-config",
    },
  ),
)
const baseProjectSchema = {
  title: Type.Optional(Type.String({ maxLength: 200 })),
  account: Type.Optional(Type.String({ default: null })),
  tags: Type.Optional(Type.Array(Type.String(), { default: [] })),
  description: Type.Optional(Type.String()),
  isDefault: Type.Optional(Type.Boolean({ default: false })),
  config: projectConfigSchema,
}

/**
 * Full Project Schema - Used for response serialization and database model
 */
export const projectSchema = Type.Object(
  {
    _id: Type.String(),
    ...baseProjectSchema,
    isDeleted: Type.Boolean({ default: false }),
    createdAt: Type.String({ format: "date-time" }),
    updatedAt: Type.String({ format: "date-time" }),
  },
  {
    $id: "#project/base",
    title: "core/project",
  },
)

/**
 * Project Create Schema - For POST operations
 */
export const projectCreateSchema = Type.Object(
  {
    _id: Type.Optional(Type.String()),
    ...baseProjectSchema,
  },
  {
    $id: "#project/create",
    title: "core/project-create",
  },
)

/**
 * Project Update Schema - For PATCH operations
 */
export const projectUpdateSchema = Type.Object(
  {
    _id: Type.Optional(Type.String()),
    ...baseProjectSchema,
  },
  {
    $id: "#project/update",
    title: "core/project-update",
  },
)

/**
 * Type Utilities
 */

type DateTimeFields = {
  createdAt: Date
  updatedAt: Date
}

type RawProject = Static<typeof projectSchema>
export type Project = Omit<RawProject, keyof DateTimeFields> & DateTimeFields

type RawProjectCreate = Static<typeof projectCreateSchema>
export type ProjectCreate = RawProjectCreate

type RawProjectUpdate = Static<typeof projectUpdateSchema>
export type ProjectUpdate = RawProjectUpdate

export interface ProjectDoc extends Document, Project {
  _id: string
}
export type AnyProject = Project | ProjectDoc

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

  fastify.registerSchema({
    schema: projectCreateSchema,
    name: "ProjectCreate",
  })

  fastify.registerSchema({
    schema: projectUpdateSchema,
    name: "ProjectUpdate",
  })
  fastify.registerSchema({
    schema: projectConfigSchema,
    name: "ProjectConfig",
  })
}
