import MyUserManager from '@caj/user/MyUserManager';
import {IDBPDatabase, IDBPTransaction, StoreNames} from 'idb';
import DBSchemas from './schemas';

import {databaseConf, databaseNames} from './types';

interface migrationArguments {
  db: IDBPDatabase<unknown>;
  oldVersion: number;
  newVersion: number | null;
  transaction: IDBPTransaction<unknown, StoreNames<unknown>[], 'versionchange'>;
  event: IDBVersionChangeEvent;
}

type upgradeFunc = (
  database: IDBPDatabase<unknown>,
  oldVersion: number,
  newVersion: number | null,
  transaction: IDBPTransaction<unknown, StoreNames<unknown>[], 'versionchange'>,
  event: IDBVersionChangeEvent,
) => void;

export const DBMigration: {[key in databaseNames]: any} = {
  users: (Schema: databaseConf<typeof DBSchemas.users.defaultProps>) => {
    const callback: upgradeFunc = (
      db,
      oldVersion,
      newVersion,
      transaction,
      event,
    ) => {
      if (oldVersion == 0) {
        // perform the initialization
        db.createObjectStore(Schema.details.name, {
          keyPath: Schema.details.primaryKey,
        });
      } else if (newVersion !== null) {
        let ver = oldVersion;

        while (ver < newVersion) {
          console.log('upgrade from v', ver, ' to v', ver + 1);

          ver++;
        }
      }
    };

    return callback;
  },
  chat: (Schema: databaseConf<typeof DBSchemas.chat.defaultProps>) => {
    const callback: upgradeFunc = (
      db,
      oldVersion,
      newVersion,
      transaction,
      event,
    ) => {
      if (oldVersion == 0) {
        // perform the initialization
        db.createObjectStore(Schema.details.name, {
          keyPath: Schema.details.primaryKey,
        });
      } else if (newVersion !== null) {
        let ver = oldVersion;

        while (ver < newVersion) {
          console.log('upgrade from v', ver, ' to v', ver + 1);

          ver++;
        }
      }
    };

    return callback;
  },
};
