import { describe, it, expect, beforeEach, afterEach } from "vitest"
import { loadConfig } from "../src/config.ts"

describe("loadConfig", () => {
  let savedToken: string | undefined
  let savedChatId: string | undefined

  beforeEach(() => {
    savedToken = process.env.TELEGRAM_BOT_TOKEN
    savedChatId = process.env.TELEGRAM_CHAT_ID
    delete process.env.TELEGRAM_BOT_TOKEN
    delete process.env.TELEGRAM_CHAT_ID
  })

  afterEach(() => {
    if (savedToken === undefined) {
      delete process.env.TELEGRAM_BOT_TOKEN
    } else {
      process.env.TELEGRAM_BOT_TOKEN = savedToken
    }
    if (savedChatId === undefined) {
      delete process.env.TELEGRAM_CHAT_ID
    } else {
      process.env.TELEGRAM_CHAT_ID = savedChatId
    }
  })

  it("returns {token, chatId} when both env vars present", () => {
    process.env.TELEGRAM_BOT_TOKEN = "tok"
    process.env.TELEGRAM_CHAT_ID = "cid"
    expect(loadConfig()).toEqual({ token: "tok", chatId: "cid" })
  })

  it("throws when token missing", () => {
    process.env.TELEGRAM_CHAT_ID = "cid"
    expect(() => loadConfig()).toThrow(/TELEGRAM_BOT_TOKEN/)
  })

  it("throws when chatId missing without override", () => {
    process.env.TELEGRAM_BOT_TOKEN = "tok"
    expect(() => loadConfig()).toThrow(/chat_id/)
  })

  it("override chatId takes priority over env", () => {
    process.env.TELEGRAM_BOT_TOKEN = "tok"
    process.env.TELEGRAM_CHAT_ID = "env-id"
    expect(loadConfig({ chatId: "argv-id" })).toEqual({ token: "tok", chatId: "argv-id" })
  })

  it("override chatId works even when env chatId missing", () => {
    process.env.TELEGRAM_BOT_TOKEN = "tok"
    expect(loadConfig({ chatId: "argv-id" })).toEqual({ token: "tok", chatId: "argv-id" })
  })
})