import { ipcMain } from 'electron';
import { createHandler } from '../database/LocalSystem.js';
import SeriesSync, { SeriesSyncUploadPayload, SeriesSyncResult, CompleteSeries, SyncedSeries } from '../database/models/SeriesSync.js';
import { SyncElementType } from '../database/repositories/series-sync.repo.js';

interface UploadToSeriesData {
    type: SyncElementType;
    bookElementId: string;
    field: string;
    value: string;
}

ipcMain.handle('db:series:sync:upload', createHandler<UploadToSeriesData, SeriesSyncResult>(
    function(userId: string, data: UploadToSeriesData, lang: 'fr' | 'en'): SeriesSyncResult {
        const payload: SeriesSyncUploadPayload = {
            type: data.type,
            bookElementId: data.bookElementId,
            field: data.field,
            value: data.value || ''
        };
        return SeriesSync.uploadFieldToSeries(userId, payload, lang);
    }
));

ipcMain.handle('db:series:synced', createHandler<void, SyncedSeries[]>(
    function(userId: string, _data: void, lang: 'fr' | 'en'): SyncedSeries[] {
        return SeriesSync.getSyncedSeries(userId, lang);
    }
));

ipcMain.handle('db:series:uploadToServer', createHandler<string, CompleteSeries>(
    async function(userId: string, seriesId: string, lang: 'fr' | 'en'): Promise<CompleteSeries> {
        return SeriesSync.getCompleteSeriesForUpload(userId, seriesId, lang);
    }
));

ipcMain.handle('db:series:syncSave', createHandler<CompleteSeries, boolean>(
    async function(userId: string, completeSeries: CompleteSeries, lang: 'fr' | 'en'): Promise<boolean> {
        return SeriesSync.saveCompleteSeries(userId, completeSeries, lang);
    }
));

ipcMain.handle('db:series:sync:toClient', createHandler<CompleteSeries, boolean>(
    async function(userId: string, completeSeries: CompleteSeries, lang: 'fr' | 'en'): Promise<boolean> {
        return SeriesSync.syncSeriesFromServerToClient(userId, completeSeries, lang);
    }
));

ipcMain.handle('db:series:sync:toServer', createHandler<object, CompleteSeries>(
    async function(userId: string, syncCompare: object, lang: 'fr' | 'en'): Promise<CompleteSeries> {
        const seriesId = (syncCompare as { id: string }).id;
        return SeriesSync.getCompleteSeriesForUpload(userId, seriesId, lang);
    }
));
