import type { DB } from "@/internal/datastore/db";
import type { Kysely } from "kysely";
import type { CityMatchConfig } from "@/internal/repository/members/city-matching";

const CACHE_TTL_MS = 60_000;

let cached: { config: CityMatchConfig; expiresAt: number } | null = null;

export class CityAliasRepository {
    private db: Kysely<DB>;

    constructor(db: Kysely<DB>) {
        this.db = db;
    }

    async loadConfig(): Promise<CityMatchConfig> {
        if (cached && cached.expiresAt > Date.now()) return cached.config;
        const [aliases, rules] = await Promise.all([
            this.db.selectFrom("city_aliases").select(["country_key", "city_key", "alias_key"]).execute(),
            this.db
                .selectFrom("city_rules")
                .select(["country_key", "city_key", "include_sub_areas", "exclude_keys", "include_state", "state_exclude_keys"])
                .execute(),
        ]);
        const config: CityMatchConfig = { aliases, rules };
        cached = { config, expiresAt: Date.now() + CACHE_TTL_MS };
        return config;
    }

    static invalidate() {
        cached = null;
    }
}
