import {QueryType} from "./index.js"

export interface UserTable {
    createUserOrUpdateActiveTime(id: string): Promise<void>

    getUserExistsAndIsAdmin(id: string): Promise<boolean>

    createOrSetUserAsAdmin(id: string): Promise<void>
}

export class UserTableImpl implements UserTable {
    private readonly _query: QueryType

    constructor({query}: { query: QueryType }) {
        this._query = query
    }

    async createUserOrUpdateActiveTime(id: string): Promise<void> {
        await this._query<{ id: string }, [string]>(
            `INSERT INTO users (id, is_admin, created_at, updated_at, active_at)
             VALUES ($1, FALSE, now(), now(), now())
             ON CONFLICT (id) DO UPDATE SET active_at = now()
             RETURNING id;`, [id])
    }

    async getUserExistsAndIsAdmin(id: string): Promise<boolean> {
        const result = await this._query<{ is_admin: boolean }, [string]>(
            `UPDATE users
             SET active_at = NOW()
             WHERE id = $1
             RETURNING is_admin;`, [id])
        if (result.rowCount === 0) {
            return false
        }
        return result.rows[0].is_admin
    }

    async createOrSetUserAsAdmin(id: string): Promise<void> {
        await this._query<{}, [string]>(
            `INSERT INTO users (id, is_admin, created_at, updated_at)
             VALUES ($1, TRUE, now(), now())
             ON CONFLICT (id) DO UPDATE SET is_admin   = TRUE,
                                            updated_at = NOW()
             WHERE users.is_admin = FALSE;`, [id])
    }
}

