import { revalidateTag } from "next/cache"
import { headers } from "next/headers"

import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import { badRequest, internalServerError } from "@/server/errors/next"

import { generateTag } from "@/utils/generateTag"

// This file is primarily to be used locally to test
// purging your cache for new (and old) requests
export async function POST() {
  try {
    const headersList = headers()
    const secret = headersList.get("x-revalidate-secret")

    if (secret !== env.REVALIDATE_SECRET) {
      console.error(`Invalid Secret`)
      console.error({ secret })
      return badRequest({
        now: Date.now(),
        revalidated: false,
      })
    }

    const affix = headersList.get("x-affix")
    const identifier = headersList.get("x-identifier")
    const lang = headersList.get("x-lang")
    if (lang && identifier) {
      if (affix) {
        const tag = generateTag(lang as Lang, identifier, affix)
        console.info(
          `Revalidated tag for [lang: ${lang}, identifier: ${identifier}, affix: ${affix}]`
        )
        console.info(`Tag: ${tag}`)
        revalidateTag(tag)
      } else {
        const tag = generateTag(lang as Lang, identifier)
        console.info(
          `Revalidated tag for [lang: ${lang}, identifier: ${identifier}]`
        )
        console.info(`Tag: ${tag}`)
        revalidateTag(tag)
      }
    } else {
      console.info(`Missing lang and/or identifier`)
      console.info(`lang: ${lang}, identifier: ${identifier}`)
      return badRequest({
        now: Date.now(),
        revalidated: false,
      })
    }

    return Response.json({ revalidated: true, now: Date.now() })
  } catch (error) {
    console.error("Failed to revalidate tag(s)")
    console.error(error)
    return internalServerError({ revalidated: false, now: Date.now() })
  }
}
