import { config } from "../../config.js";
export class MasterDataService {
    repo;
    cache;
    constructor(repo, cache) {
        this.repo = repo;
        this.cache = cache;
    }
    async list(domain, filter) {
        const key = `master:list:${domain}:${filter.page}:${filter.limit}:${filter.q ?? ""}:${filter.parentId ?? ""}:${filter.isActive ?? ""}`;
        const cached = await this.cache.get(key);
        if (cached)
            return cached;
        const page = await this.repo.list(domain, filter);
        await this.cache.set(key, page, config.masterTtlSeconds);
        return page;
    }
    async getById(domain, id) {
        const key = `master:item:${domain}:${id}`;
        const cached = await this.cache.get(key);
        if (cached)
            return cached;
        const record = await this.repo.getById(domain, id);
        if (record) {
            await this.cache.set(key, record, config.masterTtlSeconds);
        }
        return record;
    }
    async create(domain, data) {
        const record = await this.repo.create(domain, data);
        await this.cache.delByPrefix(`master:list:${domain}:`);
        return record;
    }
    async update(domain, id, data) {
        const record = await this.repo.update(domain, id, data);
        await Promise.all([
            this.cache.delByPrefix(`master:list:${domain}:`),
            this.cache.delByPrefix(`master:item:${domain}:${id}`),
        ]);
        return record;
    }
    async softDelete(domain, id) {
        const deleted = await this.repo.softDelete(domain, id);
        await Promise.all([
            this.cache.delByPrefix(`master:list:${domain}:`),
            this.cache.delByPrefix(`master:item:${domain}:${id}`),
        ]);
        return deleted;
    }
}
