import "dotenv/config"
import { prisma } from "../src/server/db"

type DomainVerifyResponse = {
  domains?: Array<{
    domain?: {
      dkim_verified?: boolean
      dkim_selector?: string
      rpath_verified?: boolean
      rpath_selector?: string
    }
  }>
}

const API_KEY = process.env.SMTP2GO_API_KEY
if (!API_KEY) throw new Error("Missing SMTP2GO_API_KEY")

async function smtp2goPost<T>(path: string, body: Record<string, unknown>): Promise<T> {
  const res = await fetch(`https://api.smtp2go.com/v3${path}`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "accept": "application/json",
      "X-Smtp2go-Api-Key": API_KEY,
    } as Record<string, string>,
    body: JSON.stringify(body),
  })
  const json = (await res.json().catch(() => ({}))) as { data?: T; error?: string }
  if (!res.ok) {
    throw new Error(json?.error || `SMTP2GO_HTTP_${res.status}`)
  }
  return (json?.data ?? (json as unknown)) as T
}

const args = new Set(process.argv.slice(2))
const limitArg = process.argv.find((a) => a.startsWith("--limit="))
const limit = limitArg ? Number(limitArg.split("=")[1]) : undefined

async function main() {
  const rows = await prisma.subaccountMeta.findMany({
    where: { domain: { not: null } },
    select: { subaccountId: true, domain: true },
  })
  const targets = limit ? rows.slice(0, limit) : rows

  let updated = 0
  let failed = 0

  for (const row of targets) {
    const subId = row.subaccountId
    const domain = row.domain?.trim()
    if (!domain) continue
    try {
      const res = await smtp2goPost<DomainVerifyResponse>("/domain/verify", {
        domain,
        subaccount_id: subId,
      })
      const entry = res?.domains?.[0]?.domain ?? {}
      await prisma.subaccountMeta.update({
        where: { subaccountId: subId },
        data: {
          dkimVerified: entry?.dkim_verified ?? null,
          rpathVerified: entry?.rpath_verified ?? null,
          dkimSelector: entry?.dkim_selector ?? null,
          rpathSelector: entry?.rpath_selector ?? null,
          domainCheckedAt: new Date(),
        },
      })
      updated++
      await new Promise((r) => setTimeout(r, 150))
    } catch (e) {
      failed++
      console.error("Falha ao verificar domínio", subId, e)
    }
  }

  console.log(`Atualizados: ${updated}`)
  console.log(`Falhas: ${failed}`)
}

main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
