/**
 * TypeORM DataSource used by the CLI migration tools (generate / run / revert).
 *
 * At **runtime** the DataSource is constructed inside `main.ts` and
 * pointed at the user's Electron `userData` directory instead.
 *
 * For CLI use, the database is stored at the project root (`metoyou.sqlite`)
 * so TypeORM can diff entity metadata against the current schema when
 * generating new migrations.
 */
import 'reflect-metadata';
import { DataSource } from 'typeorm';
import * as path from 'path';
import * as fs from 'fs';
import { settings } from './settings';
import {
  MessageEntity,
  UserEntity,
  RoomEntity,
  RoomChannelEntity,
  RoomMemberEntity,
  RoomRoleEntity,
  RoomUserRoleEntity,
  RoomChannelPermissionEntity,
  ReactionEntity,
  BanEntity,
  AttachmentEntity,
  MetaEntity,
  PluginDataEntity
} from './entities';

const projectRootDatabaseFilePath = path.join(__dirname, '..', '..', settings.databaseName);

let databaseFileBuffer: Uint8Array | undefined;

if (fs.existsSync(projectRootDatabaseFilePath)) {
  databaseFileBuffer = fs.readFileSync(projectRootDatabaseFilePath);
}

export const AppDataSource = new DataSource({
  type: 'sqljs',
  database: databaseFileBuffer,
  entities: [
    MessageEntity,
    UserEntity,
    RoomEntity,
    RoomChannelEntity,
    RoomMemberEntity,
    RoomRoleEntity,
    RoomUserRoleEntity,
    RoomChannelPermissionEntity,
    ReactionEntity,
    BanEntity,
    AttachmentEntity,
    MetaEntity,
    PluginDataEntity
  ],
  migrations: [path.join(__dirname, 'migrations', '*.{ts,js}')],
  synchronize: false,
  logging: false,
  autoSave: true,
  location: projectRootDatabaseFilePath
});
