import 'reflect-metadata'

import { app } from 'electron'
import { join } from 'path'
import { DataSource } from 'typeorm'

import { ClassEntitySchema } from '../entities/ClassEntity'
import { StudentProfileEntitySchema } from '../entities/StudentProfileEntity'
import { TemplateEntitySchema } from '../entities/TemplateEntity'
import { ReportEntitySchema } from '../entities/ReportEntity'

const DATABASE_FILENAME = 'growth-report.sqlite'

let dataSource: DataSource | null = null

function getDatabasePath(): string {
  return join(app.getPath('userData'), DATABASE_FILENAME)
}

export async function getAppDataSource(): Promise<DataSource> {
  if (dataSource?.isInitialized) {
    return dataSource
  }

  dataSource = new DataSource({
    type: 'better-sqlite3',
    database: getDatabasePath(),
    entities: [
      ClassEntitySchema,
      StudentProfileEntitySchema,
      TemplateEntitySchema,
      ReportEntitySchema
    ],
    synchronize: true,
    logging: false,
    prepareDatabase(database): void {
      database.pragma('journal_mode = WAL')
      database.pragma('foreign_keys = ON')
      database.exec('DROP INDEX IF EXISTS idx_child_profiles_class_id')
    }
  })

  await dataSource.initialize()
  console.info(
    '[数据库] 已注册实体',
    dataSource.entityMetadatas.map((metadata) => metadata.name)
  )
  return dataSource
}
