import Dexie from 'dexie'

export interface Migrations {
    [storageKey: string]: (db: Dexie) => Promise<void>
}

export const migrations: Migrations = {
    /**
     * If lastEdited is undefined, then set it to createdWhen value.
     */
    'annots-created-when-to-last-edited': async db => {
        await db
            .table('annotations')
            .toCollection()
            .filter(
                annot =>
                    annot.lastEdited == null ||
                    (Object.keys(annot.lastEdited).length === 0 &&
                        annot.lastEdited.constructor === Object),
            )
            .modify(annot => {
                annot.lastEdited = annot.createdWhen
            })
    },
}

import Dexie from 'dexie'
import normalize from 'src/util/encode-url-for-id'

export interface Migrations {
    [storageKey: string]: (db: Dexie) => Promise<void>
}

export const migrations: Migrations = {
    /**
     * If pageUrl is undefined, then re-derive it from url field.
     */
    'annots-undefined-pageUrl-field': async db => {
        await db
            .table('annotations')
            .toCollection()
            .filter(annot => annot.pageUrl === undefined)
            .modify(annot => {
                annot.pageUrl = normalize(annot.url)
            })
    },
    /**
     * If lastEdited is undefined, then set it to createdWhen value.
     */
    'annots-created-when-to-last-edited': async db => {
        await db
            .table('annotations')
            .toCollection()
            .filter(
                annot =>
                    annot.lastEdited == null ||
                    (Object.keys(annot.lastEdited).length === 0 &&
                        annot.lastEdited.constructor === Object),
            )
            .modify(annot => {
                annot.lastEdited = annot.createdWhen
            })
    },
}

Add "quick-and-dirty" migration to rederive missing annot `pageUrl` fields
Add "quick-and-dirty" migration to rederive missing annot `pageUrl` fields

- due to the update issue, users may have annots data with `pageUrl` fields set to `undefined`
- annots search will crash with data like this as it assumes `pageUrl` field is always available
- "quick-and-dirty" migrations already set up to run once on the next update (unless user manually removes flag from local storage)
