import "dotenv/config"

import { createPrismaClient } from "./utils/prisma-client.mjs"

const prisma = createPrismaClient()

const statements = [
  `ALTER TABLE "Company" ADD COLUMN "legalName" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "tradeName" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "stateRegistration" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "stateRegistrationType" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "primaryCnae" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "timezone" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "businessHours" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "supportEmail" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "billingEmail" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "contactPreferences" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "clientDomains" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "communicationChannels" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "fiscalAddress" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "hasBranches" BOOLEAN NOT NULL DEFAULT false`,
  `ALTER TABLE "Company" ADD COLUMN "regulatedEnvironments" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "privacyPolicyAccepted" BOOLEAN NOT NULL DEFAULT false`,
  `ALTER TABLE "Company" ADD COLUMN "privacyPolicyReference" TEXT`,
  `ALTER TABLE "Company" ADD COLUMN "privacyPolicyMetadata" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "contracts" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "contacts" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "locations" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "sla" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "tags" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "customFields" JSON`,
  `ALTER TABLE "Company" ADD COLUMN "notes" TEXT`,
]

async function main() {
  for (const statement of statements) {
    try {
      await prisma.$executeRawUnsafe(statement)
    } catch (error) {
      // Ignore errors caused by columns that already exist (idempotent execution)
      if (
        !(error instanceof Error) ||
        !/duplicate column name|already exists/i.test(error.message ?? "")
      ) {
        console.error(`Failed to apply migration statement: ${statement}`)
        throw error
      }
    }
  }
}

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