import { query } from "../sql/query";

/**
 * 账号状态上报模型
 * 用于存储和查询账号的上报状态
 */
class AccountStatusModel {
    /**
     * 查询账号状态
     * @param account 账号
     * @param channelId 渠道ID
     * @returns 账号状态记录
     */
    async getAccountStatus(account: string, channelId: number) {
        try {
            const result = await query(
                `SELECT * FROM account_status WHERE account = ? AND channel_id = ?`,
                [account, channelId]
            );
            return Array.isArray(result) && result.length > 0 ? result[0] : null;
        } catch (error) {
            const logger = require("../utils/log");
            logger.error("查询账号状态失败:", error);
            throw error;
        }
    }

    /**
     * 创建或更新账号状态
     * @param account 账号
     * @param channelId 渠道ID
     * @param status 上报状态
     * @returns 操作结果
     */
    async upsertAccountStatus(account: string, channelId: number, status: number) {
        try {
            const now = new Date().toISOString().slice(0, 19).replace('T', ' ');
            
            // 先查询是否存在
            const existing = await this.getAccountStatus(account, channelId);
            
            if (existing) {
                // 更新
                const result = await query(
                    `UPDATE account_status SET status = ?, updated_at = ? WHERE account = ? AND channel_id = ?`,
                    [status, now, account, channelId]
                );
                return result;
            } else {
                // 插入
                const result = await query(
                    `INSERT INTO account_status (account, channel_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`,
                    [account, channelId, status, now, now]
                );
                return result;
            }
        } catch (error) {
            const logger = require("../utils/log");
            logger.error("保存账号状态失败:", error);
            throw error;
        }
    }

    /**
     * 批量查询账号状态
     * @param accounts 账号数组
     * @param channelId 渠道ID
     * @returns 账号状态记录数组
     */
    async getAccountStatusBatch(accounts: string[], channelId: number) {
        try {
            if (!accounts || accounts.length === 0) {
                return [];
            }
            
            const placeholders = accounts.map(() => '?').join(',');
            const result = await query(
                `SELECT * FROM account_status WHERE account IN (${placeholders}) AND channel_id = ?`,
                [...accounts, channelId]
            );
            return Array.isArray(result) ? result : [];
        } catch (error) {
            const logger = require("../utils/log");
            logger.error("批量查询账号状态失败:", error);
            throw error;
        }
    }
}

module.exports = new AccountStatusModel();

