import { Arg, AutoObjectType, Int, Mutation, Query, Resolver } from "@aet/gql-tools/macro"
import { login, logout, remoteDb } from "../../couchdb"

@AutoObjectType()
class DatabaseInfo {
  dbName!: string
  diskFormatVersion?: Int
  docCount!: Int
  docDeleteCount?: Int
  idbAttachmentFormat?: string
  instantStartTime?: string
  purgeSeq?: string
  sizes?: DatabaseSize
  sqlitePlugin?: boolean
  updateSeq?: string
}

@AutoObjectType()
class DatabaseSize {
  active!: Int
  external!: Int
  file!: Int
}

@Resolver()
export class CloudResolver {
  @Query()
  async remoteInfo(): Promise<DatabaseInfo | undefined> {
    if (!remoteDb) return

    try {
      const info = await remoteDb.info()
      return {
        dbName: info.db_name,
        diskFormatVersion: (info as any).disk_format_version,
        docCount: info.doc_count,
        docDeleteCount: (info as any).doc_del_count,
        idbAttachmentFormat: info.idb_attachment_format,
        instantStartTime: (info as any).instant_start_time,
        purgeSeq: (info as any).purge_seq,
        sizes: (info as any).sizes,
        sqlitePlugin: info.sqlite_plugin,
        updateSeq: String(info.update_seq),
      }
    } catch {}
  }

  @Mutation()
  async login(@Arg() username: string, @Arg() password: string): Promise<boolean> {
    const db = login(username, password)
    try {
      await db.info()
      return true
    } catch {
      return false
    }
  }

  @Mutation()
  logout(): boolean {
    logout()
    return true
  }
}
