import Dexie, { type Table } from 'dexie';

export interface PendingScan {
    id?: number;
    temp_id: string; // Used to link tasting notes before sync
    imageBase64: string;
    timestamp: number;
    provider?: 'gemini' | 'openrouter';
    locale?: string;
    metadata?: any; // Bottle metadata for offline scans
    syncing?: number; // 0 or 1 for indexing
    attempts?: number;
    last_error?: string;
    bgRemoved?: boolean;
}

export interface PendingTasting {
    id?: number;
    bottle_id?: string; // Real ID if already exists
    pending_bottle_id?: string; // Temp ID of a pending scan
    data: {
        session_id?: string;
        rating: number;
        nose_notes?: string;
        palate_notes?: string;
        finish_notes?: string;
        is_sample?: boolean;
        buddy_ids?: string[];
        tag_ids?: string[];
    };
    photo?: string;
    tasted_at: string;
    syncing?: number; // 0 or 1 for indexing
    attempts?: number;
    last_error?: string;
}

export interface CachedTag {
    id: string;
    name: string;
    category: string;
    is_system_default: boolean;
    popularity_score: number;
}

export interface CachedBuddy {
    id: string;
    name: string;
}

export interface CachedBottle {
    id: string;
    name: string;
    distillery: string;
    category: string;
    abv: number;
    age: number;
    whiskybase_id: string | null;
    image_url: string;
    purchase_price?: number | null;
    status?: string | null;
    distilled_at?: string | null;
    bottled_at?: string | null;
    batch_info?: string | null;
    created_at: string;
    updated_at: string;
    bgRemoved?: boolean;
}

export interface CachedTasting {
    id: string;
    bottle_id: string;
    user_id: string;
    rating: number;
    nose_notes?: string;
    palate_notes?: string;
    finish_notes?: string;
    is_sample: boolean;
    created_at: string;
    tasted_at?: string;
    tasting_sessions?: { id: string; name: string };
    tasting_tags?: { tags: { id: string; name: string; category: string } }[];
}

export class WhiskyDexie extends Dexie {
    pending_scans!: Table<PendingScan>;
    pending_tastings!: Table<PendingTasting>;
    cache_tags!: Table<CachedTag>;
    cache_buddies!: Table<CachedBuddy>;
    cache_bottles!: Table<CachedBottle>;
    cache_tastings!: Table<CachedTasting>;

    constructor() {
        super('WhiskyVault');
        this.version(7).stores({
            pending_scans: '++id, temp_id, timestamp, locale, syncing, attempts',
            pending_tastings: '++id, bottle_id, pending_bottle_id, tasted_at, syncing, attempts',
            cache_tags: 'id, category, name',
            cache_buddies: 'id, name',
            cache_bottles: 'id, distillery, category, status, purchase_price',
            cache_tastings: 'id, bottle_id, session_id, tasted_at',
        });
    }
}

export const db = new WhiskyDexie();
