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' | 'mistral';
    locale?: string;
}

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;
}

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;
    image_url?: string;
    whiskybase_id?: string;
    distilled_at?: string;
    bottled_at?: string;
    batch_info?: string;
    last_updated: number;
}

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(4).stores({
            pending_scans: '++id, temp_id, timestamp, locale',
            pending_tastings: '++id, bottle_id, pending_bottle_id, tasted_at',
            cache_tags: 'id, category, name',
            cache_buddies: 'id, name',
            cache_bottles: 'id, name, distillery',
            cache_tastings: 'id, bottle_id, created_at'
        });
    }
}

export const db = new WhiskyDexie();
