import {Database, RunResult, SQLiteValue} from 'node-sqlite3-wasm';
import System from "../System";

export interface UserInfosQueryResponse extends Record<string, SQLiteValue> {
    first_name: string;
    last_name: string;
    username: string;
    email: string;
    plateform: string;
    term_accepted: number;
    account_verified: number;
    user_meta: string;
    author_name: string;
    writing_lang: number,
    writing_level: number,
    rite_points: number,
    user_group: number,
    credits_balance: number,
}

export interface CredentialResponse {
    valid: boolean;
    message?: string;
    user?: UserResponse;
}

interface UserResponse {
    id: string;
    name: string;
    last_name: string;
    username: string;
    email: string;
    account_verified: boolean;
}

export interface UserQueryResponse extends Record<string, SQLiteValue> {
    user_id: string;
    first_name: string;
    last_name: string;
    username: string;
    email: string;
    plateform: string;
    accountVerified: boolean;
    password: string;
}

export interface UserAccountQuery extends Record<string, SQLiteValue> {
    first_name: string;
    last_name: string;
    username: string
    author_name: string;
    email: string;
    user_meta: string;
}

export interface TOTPQuery extends Record<string, SQLiteValue> {
    user_id: number;
    email: string;
    totp_code: string;
    totp_meta: string;
}

export interface PasswordResponse extends Record<string, SQLiteValue> {
    user_id: string;
    password: string;
}

export interface GuideTourResult extends Record<string, SQLiteValue> {
    step_tour: string;
}

export interface UserSubscription extends Record<string, SQLiteValue> {
    user_id: string;
    sub_type: string;
    sub_tier: number;
    start_date: string;
    end_date: string;
    status: number;
}

export interface UserAPIKeyResult extends Record<string, SQLiteValue> {
    brand: AIBrand,
    key: string | null,
    actif: number
}

export interface UserAiUsageResult extends Record<string, SQLiteValue> {
    token_in: string;
    token_out: string;
    total_price: number;
}

export interface BasicUserCredentials extends Record<string, SQLiteValue> {
    user_id: string,
    first_name: string,
    last_name: string,
    username: string,
    email: string,
    user_meta: string
}

export default class UserRepo {
    public static updatePoints(points: number, userId: string, lang: 'fr' | 'en' = 'fr'): void {
        try {
            const db: Database = System.getDb();
            db.run('UPDATE `erit_users` SET `erite_points`=erite_points+? WHERE `user_id`=?', [points, userId]);
        } catch (e: unknown) {
            if (e instanceof Error) {
                console.error(`DB Error: ${e.message}`);
                throw new Error(lang === 'fr' ? `Impossible de mettre à jour les points.` : `Unable to update points.`);
            } else {
                console.error("An unknown error occurred.");
                throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
            }
        }
    }

    public static insertUser(uuId: string, firstName: string, lastName: string, username: string, originUsername: string, email: string, originEmail: string, password: string, meta: string, socialId: string | null, provider: string, lang: 'fr' | 'en' = 'fr'): string {
        let result: RunResult;
        try {
            const db: Database = System.getDb();
            const query = `INSERT INTO erit_users (user_id, first_name, last_name, username, email, origin_email,
                                                   origin_username, plateform, social_id, password, term_accepted,
                                                   account_verified, user_meta)
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?)`;
            const values: (string | null | number)[] = [uuId, firstName, lastName, username, email, originEmail, originUsername, provider, socialId, password, meta];
            result = db.run(query, values);
        } catch (e: unknown) {
            if (e instanceof Error) {
                console.error(`DB Error: ${e.message}`);
                throw new Error(lang === 'fr' ? `Impossible d'enregistrer l'utilisateur.` : `Unable to register user.`);
            } else {
                console.error("An unknown error occurred.");
                throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
            }
        }
        if (result.changes > 0) {
            return uuId;
        } else {
            throw new Error(lang === 'fr' ? `Une erreur s'est produite lors de l'enregistrement de l'utilisateur.` : `Error registering user.`);
        }
    }

    public static fetchUserInfos(userId: string, lang: 'fr' | 'en' = 'fr'): UserInfosQueryResponse {
        let result;
        try {
            const db: Database = System.getDb();
            result = db.get('SELECT `first_name`, `last_name`, `username`, `email`, `plateform`, `term_accepted`, `account_verified`, user_meta, author_name, writing_lang, writing_level, erite_points AS rite_points, user_group, credits_balance  FROM `erit_users` AS users LEFT JOIN user_preferences AS preference ON users.user_id=preference.user_id WHERE users.user_id=?', [userId]);
        } catch (e: unknown) {
            if (e instanceof Error) {
                console.error(`DB Error: ${e.message}`);
                throw new Error(lang === 'fr' ? `Impossible de récupérer les informations utilisateur.` : `Unable to retrieve user information.`);
            } else {
                console.error("An unknown error occurred.");
                throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
            }
        }
        if (!result) {
            throw new Error(lang === 'fr' ? `Utilisateur non trouvé.` : `User not found.`);
        }
        return result as UserInfosQueryResponse;
    }

    public static updateUserInfos(userId: string, firstName: string, lastName: string, username: string, originUsername: string, email: string, originEmail: string, userMeta: string, originalAuthorName: string, authorName: string, lang: 'fr' | 'en' = 'fr'): boolean {
        try {
            const db: Database = System.getDb();
            const result: RunResult = db.run('UPDATE `erit_users` SET `first_name`=?, `last_name`=?, `username`=?, email=?,`origin_username`=?, user_meta=?, origin_author_name=? ,author_name=? WHERE user_id=? AND `origin_email`=?', [firstName, lastName, username, email, originUsername, userMeta, originalAuthorName, authorName, userId, originEmail]);
            return result.changes > 0;
        } catch (e: unknown) {
            if (e instanceof Error) {
                console.error(`DB Error: ${e.message}`);
                throw new Error(lang === 'fr' ? `Impossible de mettre à jour les informations utilisateur.` : `Unable to update user information.`);
            } else {
                console.error("An unknown error occurred.");
                throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
            }
        }
    }

    public static fetchAccountInformation(userId: string, lang: 'fr' | 'en' = 'fr'): UserAccountQuery {
        let result;
        try {
            const db: Database = System.getDb();
            result = db.get('SELECT `first_name`, `last_name`, `username`,`author_name`, `email`,`user_meta` FROM `erit_users` WHERE user_id=?', [userId]);
        } catch (e: unknown) {
            if (e instanceof Error) {
                console.error(`DB Error: ${e.message}`);
                throw new Error(lang === 'fr' ? `Impossible de récupérer les informations du compte.` : `Unable to retrieve account information.`);
            } else {
                console.error("An unknown error occurred.");
                throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
            }
        }
        if (!result) {
            throw new Error(lang === 'fr' ? `Compte non trouvé.` : `Account not found.`);
        }
        return result as UserAccountQuery;
    }

    static fetchGuideTour(userId: string, plateforme: string): GuideTourResult[] {
        try {
            const db: Database = System.getDb();
            const result = db.all('SELECT `step_tour` FROM `logs_guide_tour` WHERE user_id=? AND plateforme=?', [userId, plateforme]) as GuideTourResult[];
            return result.length > 0 ? result : [];
        } catch (e: unknown) {
            if (e instanceof Error) {
                console.error(e.message);
                return [];
            } else {
                console.error(`Une erreur inconnue est survenue lors de la récupération du guide tour.`);
                return [];
            }
        }
    }
}
