import Dexie, { type Table } from 'dexie';
import { browser } from '$app/environment';

import type { key_val } from '$lib/stores/ae_stores';
import type { ae_Journal, ae_JournalEntry } from '$lib/types/ae_types';
import { IDB_CONTENT_VERSIONS } from '$lib/stores/store_versions';
import { check_and_clear_idb_tables } from '$lib/ae_core/core__idb_dexie';

// li = list
// kv = key value list
// json = JSON string
// ux = user experience (mode)
// LLM = Large Language Model (AI)
// Updated 2026-01-09 - Unified Types

/**
 * Journal - A collection of journal entries
 * Related Files:
 * - src/lib/ae_journals/ae_journals__journal.ts (API)
 * - src/routes/journals/[journal_id]/+layout.svelte (View)
 * - src/routes/journals/ae_comp__journal_obj_id_view.svelte (Card View)
 */
export interface Journal extends ae_Journal {
    // Add any Dexie-specific or legacy local-only fields here if not in ae_Journal
    // Most fields are now in ae_Journal and ae_BaseObj

    // For backward compatibility with some views that expect these
    combined_passcode?: string;
    person__given_name?: string;
    person__family_name?: string;
    person__full_name?: string;
    person__primary_email?: string;
    person__passcode?: string;
    person__kv_json?: string;

    journal_entry_kv?: key_val;
    journal_entry_li?: any[];
    journal_file_kv?: key_val;
    journal_file_li?: any[];
}

export const journal_field_li = [
    'id',
    'journal_id',
    // 'journal_id_random',
    'account_id',
    // 'account_id_random',
    'person_id',
    // 'person_id_random',
    'code',
    'name',
    'short_name',
    'summary',
    'outline',
    'description',
    'type_code',
    'tags',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'tmp_sort_3'
];

/**
 * Journal_Entry - A single entry within a journal
 * Related Files:
 * - src/lib/ae_journals/ae_journals__journal_entry.ts (API)
 * - src/routes/journals/[journal_id]/entry/[journal_entry_id]/+page.svelte (View)
 * - src/routes/journals/[journal_id]/ae_comp__journal_entry_obj_qry.svelte (Search)
 */
export interface Journal_Entry extends ae_JournalEntry {
    // Add any Dexie-specific or legacy local-only fields here
    person__given_name?: string;
    person__family_name?: string;
    person__full_name?: string;
    person__primary_email?: string;
    person__passcode?: string;
    person__kv_json?: string;

    journal_file_kv?: key_val;
    journal_file_li?: any[];
}

export const journal_entry_field_li = [
    'id',
    'journal_entry_id',
    // 'journal_entry_id_random',
    'journal_id',
    // 'journal_id_random',
    'person_id',
    // 'person_id_random',
    'code',
    'name',
    'short_name',
    'summary',
    'outline',
    'content',
    'content_md_html',
    'content_encrypted',
    'enable',
    'hide',
    'priority',
    'sort',
    'group',
    'notes',
    'created_on',
    'updated_on',
    'tmp_sort_1',
    'tmp_sort_2',
    'tmp_sort_3'
];

export class MySubClassedDexie extends Dexie {
    journal!: Table<Journal>;
    journal_entry!: Table<Journal_Entry>;

    constructor() {
        super('ae_journals_db');
        this.version(5).stores({
            journal: `
                id, journal_id,
                code,
                account_id,
                person_id,
                name,
                enable, hide, priority, sort, group, created_on, updated_on`,
            journal_entry: `
                id, journal_entry_id,
                journal_id,
                person_id,
                code,
                template,
                name,
                enable, hide, priority, sort, group, created_on, updated_on`
        });
    }
}

export const db_journals = new MySubClassedDexie();

// On each page load, clear any tables whose content version has changed.
// Versions are defined in store_versions.ts IDB_CONTENT_VERSIONS.journals.
// Each table is only cleared once per version bump (tracked in localStorage).
if (browser) {
    check_and_clear_idb_tables({
        db_instance: db_journals,
        module_name: 'journals',
        table_versions: IDB_CONTENT_VERSIONS.journals
    }).catch((e) => console.warn('[db_journals] IDB version check failed:', e));
}
