// ml_oceanengine
const db = require('./Database');
const QueryBuilder = require('./QueryBuilder');

class BaseModel {
    constructor(tableName) {
        this.tableName = tableName;
        this.queryBuilder = new QueryBuilder();
    }

    async findOne(conditions) {
        this.queryBuilder.clear()
        const { sql, params } = this.queryBuilder
            .select()
            .from(this.tableName)
            .where(conditions)
            .limit(1)
            .getQuery();
        const results = await db.query(sql, params);
        return results[0] || null;
    }

    async findAll(conditions = {}, limit = null, offset = 0, orderBy = null) {
        this.queryBuilder.clear()
        let builder = this.queryBuilder
            .select()
            .from(this.tableName)
            .where(conditions);

        if (orderBy) {
            builder.orderBy(orderBy);
        }

        if (limit) {
            builder.limit(limit, offset);
        }

        const { sql, params } = builder.getQuery();
        return await db.query(sql, params);
    }

    async create(data) {
        this.queryBuilder.clear()
        const { sql, params } = this.queryBuilder
            .insert(this.tableName, data)
            .getQuery();

        const result = await db.query(sql, params);
        return result.insertId;
    }

    async update(conditions, data) {
        this.queryBuilder.clear()
        const { sql, params } = this.queryBuilder
            .update(this.tableName, data)
            .where(conditions)
            .getQuery();
        const result = await db.query(sql, params);
        return result.affectedRows;
    }

    async delete(conditions) {
        this.queryBuilder.clear()
        const { sql, params } = this.queryBuilder
            .delete(this.tableName)
            .where(conditions)
            .getQuery();

        const result = await db.query(sql, params);
        return result.affectedRows;
    }

    async transaction(callback) {
        return await db.transaction(callback);
    }
}

module.exports = BaseModel;