import type { WaGroupMetadataSnapshot, WaGroupMetadataStore } from 'zapo-js/store'

import { BaseRedisStore } from './BaseRedisStore'
import { deleteKeysChunked, scanKeys } from './helpers'
import type { WaRedisStorageOptions } from './types'

const DEFAULT_GROUP_METADATA_TTL_MS = 5 * 60 * 1000

export class WaGroupMetadataRedisStore extends BaseRedisStore implements WaGroupMetadataStore {
    private readonly ttlMs: number

    public constructor(options: WaRedisStorageOptions, ttlMs = DEFAULT_GROUP_METADATA_TTL_MS) {
        super(options)
        if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) {
            throw new Error('groupMetadata ttlMs must be a positive integer')
        }
        this.ttlMs = ttlMs
    }

    public async upsertGroupMetadata(snapshot: WaGroupMetadataSnapshot): Promise<void> {
        const key = this.k('participants', this.sessionId, snapshot.groupJid)
        const pipeline = this.redis.pipeline()
        const fields: Record<string, string> = {
            participants_json: JSON.stringify(snapshot.participants),
            updated_at_ms: String(snapshot.updatedAtMs)
        }
        if (snapshot.ephemeralTrigger === undefined) {
            pipeline.hdel(key, 'ephemeral_trigger')
        } else {
            fields.ephemeral_trigger = String(snapshot.ephemeralTrigger)
        }
        if (snapshot.ephemeral === undefined) {
            pipeline.hdel(key, 'ephemeral')
        } else {
            fields.ephemeral = String(snapshot.ephemeral)
        }
        pipeline.hset(key, fields)
        pipeline.pexpire(key, this.ttlMs)
        await pipeline.exec()
    }

    public async getGroupMetadata(
        groupJid: string,
        _nowMs?: number
    ): Promise<WaGroupMetadataSnapshot | null> {
        const key = this.k('participants', this.sessionId, groupJid)
        const data = await this.redis.hgetall(key)
        if (!data || Object.keys(data).length === 0) return null

        const parsed: unknown = JSON.parse(data.participants_json)
        if (!Array.isArray(parsed)) {
            throw new Error('participants_json must be an array')
        }

        const ephemeral = data.ephemeral === undefined ? undefined : Number(data.ephemeral)
        const ephemeralTrigger =
            data.ephemeral_trigger === undefined ? undefined : Number(data.ephemeral_trigger)
        return {
            groupJid,
            participants: parsed.map((entry: unknown) => String(entry)),
            ephemeral,
            ephemeralTrigger,
            updatedAtMs: Number(data.updated_at_ms)
        }
    }

    public async deleteGroupMetadata(groupJid: string): Promise<number> {
        const key = this.k('participants', this.sessionId, groupJid)
        return this.redis.del(key)
    }

    public async cleanupExpired(_nowMs: number): Promise<number> {
        return 0
    }

    public async clear(): Promise<void> {
        const pattern = this.k('participants', this.sessionId, '*')
        const keys = await scanKeys(this.redis, pattern)
        if (keys.length > 0) {
            await deleteKeysChunked(this.redis, keys)
        }
    }
}
