import Dexie, { type EntityTable } from 'dexie'
import type {
  ContentFile,
  EmailAddressInfo,
  EmailInject,
  EmailTemplate,
  InformationInject,
  InjectControl,
  InjectInfo,
  LearningActivityInfo,
  LearningObjectiveInfo,
  MarkdownContent,
  Milestone,
  Overlay,
  Questionnaire,
  QuestionnaireQuestion,
  ToolInfo,
  ToolResponse,
} from './types'

const dbName = 'EditorDatabase'
const dbVersion = 1

const db = new Dexie(dbName) as Dexie & {
  learningObjectives: EntityTable<LearningObjectiveInfo, 'id'>
  learningActivities: EntityTable<LearningActivityInfo, 'id'>
  injectInfos: EntityTable<InjectInfo, 'id'>
  tools: EntityTable<ToolInfo, 'id'>
  toolResponses: EntityTable<ToolResponse, 'id'>
  emailAddresses: EntityTable<EmailAddressInfo, 'id'>
  emailTemplates: EntityTable<EmailTemplate, 'id'>
  emailInjects: EntityTable<EmailInject, 'id'>
  informationInjects: EntityTable<InformationInject, 'id'>
  questionnaires: EntityTable<Questionnaire, 'id'>
  questionnaireQuestions: EntityTable<QuestionnaireQuestion, 'id'>
  overlays: EntityTable<Overlay, 'id'>
  injectControls: EntityTable<InjectControl, 'id'>
  files: EntityTable<ContentFile, 'id'>
  milestones: EntityTable<Milestone, 'id'>
  markdownContents: EntityTable<MarkdownContent, 'id'>
}

db.version(dbVersion).stores({
  learningObjectives: '++id, &name',
  learningActivities: '++id, &name, description, type, learningObjectiveId',
  injectInfos: '++id, &name, description, type',
  tools: '++id, &name, tooltipDescription, hint, defaultResponse',
  toolResponses:
    '++id, &learningActivityId, toolId, parameter, isRegex, content, fileId',
  emailAddresses: '++id, &address, organization, description, teamVisible',
  emailTemplates:
    '++id, &learningActivityId, emailAddressId, context, content, fileId',
  emailInjects:
    '++id, &injectInfoId, emailAddressId, subject, content, extraCopies, fileId',
  informationInjects: '++id, &injectInfoId, content, fileId',
  questionnaires: '++id, &injectInfoId, &title',
  questionnaireQuestions: '++id, questionnaireId, text, max, correct, labels',
  overlays: '++id, &injectInfoId, duration',
  injectControls: '++id, &injectInfoId, start, delay, milestoneCondition',
  files: '++id, &name, blob',
  milestones: '++id, [type+referenceId]',
  markdownContents: '++id, &fileName, content',
})

export { db }
