CREATE TYPE "BillingInvoiceTerms" AS ENUM (
  'DUE_ON_RECEIPT',
  'NET_7',
  'NET_15',
  'NET_30',
  'NET_45',
  'NET_60'
);

CREATE TYPE "BillingInvoiceStatus" AS ENUM (
  'DRAFT',
  'OPEN',
  'PAID',
  'PARTIALLY_PAID',
  'PAYMENT_PENDING',
  'PAST_DUE',
  'VOID',
  'UNCOLLECTIBLE',
  'REFUNDED',
  'PARTIALLY_REFUNDED'
);

CREATE TYPE "BillingInvoiceType" AS ENUM (
  'SUBSCRIPTION_INITIAL',
  'SUBSCRIPTION_RENEWAL',
  'TRIAL_CONVERSION',
  'SUBSCRIPTION_UPGRADE',
  'SUBSCRIPTION_DOWNGRADE_CREDIT',
  'USAGE_BASED',
  'ONE_TIME',
  'MANUAL',
  'CORRECTION',
  'CANCELLATION_FEE'
);

CREATE TYPE "BillingLineItemType" AS ENUM (
  'SUBSCRIPTION_FEE',
  'SEAT_FEE',
  'USAGE_FEE',
  'SETUP_FEE',
  'DISCOUNT',
  'TAX',
  'CREDIT',
  'PRORATION',
  'REFUND_ADJUSTMENT',
  'MANUAL_ADJUSTMENT',
  'PROFESSIONAL_SERVICES',
  'CANCELLATION_FEE'
);

CREATE TYPE "BillingPaymentMethodType" AS ENUM (
  'CARD',
  'ACH_DEBIT',
  'BANK_TRANSFER',
  'WIRE_TRANSFER',
  'MANUAL_INVOICE',
  'PURCHASE_ORDER'
);

CREATE TYPE "BillingPaymentIntentStatus" AS ENUM (
  'REQUIRES_PAYMENT_METHOD',
  'REQUIRES_CONFIRMATION',
  'REQUIRES_ACTION',
  'PROCESSING',
  'SUCCEEDED',
  'FAILED',
  'CANCELED',
  'REFUNDED',
  'PARTIALLY_REFUNDED'
);

CREATE TYPE "BillingPaymentAttemptStatus" AS ENUM (
  'PENDING',
  'PROCESSING',
  'SUCCEEDED',
  'FAILED',
  'CANCELED',
  'REFUNDED',
  'PARTIALLY_REFUNDED'
);

CREATE TYPE "BillingRefundStatus" AS ENUM (
  'PENDING',
  'SUCCEEDED',
  'FAILED'
);

CREATE TYPE "BillingCreditNoteStatus" AS ENUM (
  'ISSUED',
  'APPLIED',
  'VOID'
);

CREATE SEQUENCE "billing_invoice_sequence_seq" START 1;

CREATE TABLE "billing_accounts" (
  "id" TEXT NOT NULL,
  "companyId" TEXT NOT NULL,
  "isPrimary" BOOLEAN NOT NULL DEFAULT true,
  "legalName" TEXT NOT NULL,
  "billingEmail" TEXT NOT NULL,
  "billingAddress" JSONB,
  "taxId" TEXT,
  "taxExempt" BOOLEAN NOT NULL DEFAULT false,
  "defaultCurrency" TEXT NOT NULL DEFAULT 'MAD',
  "defaultPaymentMethodId" TEXT,
  "invoiceTerms" "BillingInvoiceTerms" NOT NULL DEFAULT 'DUE_ON_RECEIPT',
  "netTermsDays" INTEGER NOT NULL DEFAULT 0,
  "providerCustomerId" TEXT,
  "dunningPaused" BOOLEAN NOT NULL DEFAULT false,
  "dunningPausedAt" TIMESTAMP(3),
  "dunningPausedBy" TEXT,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_accounts_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_payment_methods" (
  "id" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "type" "BillingPaymentMethodType" NOT NULL,
  "providerPaymentMethodId" TEXT,
  "label" TEXT,
  "brand" TEXT,
  "last4" TEXT,
  "expMonth" INTEGER,
  "expYear" INTEGER,
  "isDefault" BOOLEAN NOT NULL DEFAULT false,
  "isActive" BOOLEAN NOT NULL DEFAULT true,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_payment_methods_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_invoices" (
  "id" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "companyId" TEXT NOT NULL,
  "subscriptionId" TEXT,
  "invoiceNumber" TEXT,
  "invoiceSequence" INTEGER,
  "invoiceType" "BillingInvoiceType" NOT NULL,
  "status" "BillingInvoiceStatus" NOT NULL DEFAULT 'DRAFT',
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "subtotalAmount" INTEGER NOT NULL DEFAULT 0,
  "discountAmount" INTEGER NOT NULL DEFAULT 0,
  "creditAmount" INTEGER NOT NULL DEFAULT 0,
  "taxAmount" INTEGER NOT NULL DEFAULT 0,
  "totalAmount" INTEGER NOT NULL DEFAULT 0,
  "amountPaid" INTEGER NOT NULL DEFAULT 0,
  "amountDue" INTEGER NOT NULL DEFAULT 0,
  "invoiceDate" TIMESTAMP(3),
  "dueAt" TIMESTAMP(3),
  "finalizedAt" TIMESTAMP(3),
  "paidAt" TIMESTAMP(3),
  "voidedAt" TIMESTAMP(3),
  "markedUncollectibleAt" TIMESTAMP(3),
  "billingName" TEXT,
  "billingEmail" TEXT,
  "billingAddress" JSONB,
  "providerInvoiceId" TEXT,
  "paymentProvider" "PaymentProvider",
  "isSubscriptionBlocking" BOOLEAN NOT NULL DEFAULT false,
  "adminReason" TEXT,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdByAdminId" TEXT,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_invoices_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_invoice_line_items" (
  "id" TEXT NOT NULL,
  "invoiceId" TEXT NOT NULL,
  "subscriptionId" TEXT,
  "plan" "Plan",
  "type" "BillingLineItemType" NOT NULL,
  "description" TEXT NOT NULL,
  "quantity" INTEGER NOT NULL DEFAULT 1,
  "unitAmount" INTEGER NOT NULL,
  "amount" INTEGER NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "periodStart" TIMESTAMP(3),
  "periodEnd" TIMESTAMP(3),
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_invoice_line_items_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_payment_intents" (
  "id" TEXT NOT NULL,
  "invoiceId" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "paymentMethodId" TEXT,
  "providerPaymentIntentId" TEXT,
  "status" "BillingPaymentIntentStatus" NOT NULL DEFAULT 'REQUIRES_PAYMENT_METHOD',
  "amount" INTEGER NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_payment_intents_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_payment_attempts" (
  "id" TEXT NOT NULL,
  "invoiceId" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "paymentIntentId" TEXT,
  "paymentMethodId" TEXT,
  "providerPaymentId" TEXT,
  "status" "BillingPaymentAttemptStatus" NOT NULL,
  "amount" INTEGER NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "failureCode" TEXT,
  "failureMessage" TEXT,
  "attemptedAt" TIMESTAMP(3) NOT NULL,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_payment_attempts_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_credit_balances" (
  "id" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "balanceAmount" INTEGER NOT NULL DEFAULT 0,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_credit_balances_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_credit_ledger_entries" (
  "id" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "invoiceId" TEXT,
  "type" TEXT NOT NULL,
  "amount" INTEGER NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "reason" TEXT NOT NULL,
  "createdBy" TEXT,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_credit_ledger_entries_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_credit_notes" (
  "id" TEXT NOT NULL,
  "invoiceId" TEXT NOT NULL,
  "billingAccountId" TEXT NOT NULL,
  "amount" INTEGER NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "reason" TEXT NOT NULL,
  "status" "BillingCreditNoteStatus" NOT NULL DEFAULT 'ISSUED',
  "createdBy" TEXT,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_credit_notes_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_refunds" (
  "id" TEXT NOT NULL,
  "invoiceId" TEXT NOT NULL,
  "paymentAttemptId" TEXT,
  "billingAccountId" TEXT NOT NULL,
  "amount" INTEGER NOT NULL,
  "currency" TEXT NOT NULL DEFAULT 'MAD',
  "reason" TEXT NOT NULL,
  "status" "BillingRefundStatus" NOT NULL DEFAULT 'PENDING',
  "providerRefundId" TEXT,
  "createdBy" TEXT,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_refunds_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_tax_records" (
  "id" TEXT NOT NULL,
  "invoiceId" TEXT NOT NULL,
  "jurisdiction" TEXT,
  "taxRate" DOUBLE PRECISION,
  "taxAmount" INTEGER NOT NULL,
  "taxType" TEXT,
  "taxExempt" BOOLEAN NOT NULL DEFAULT false,
  "exemptionReason" TEXT,
  "providerTaxId" TEXT,
  "metadata" JSONB NOT NULL DEFAULT '{}',
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_tax_records_pkey" PRIMARY KEY ("id")
);

CREATE TABLE "billing_events" (
  "id" TEXT NOT NULL,
  "billingAccountId" TEXT,
  "invoiceId" TEXT,
  "subscriptionId" TEXT,
  "companyId" TEXT,
  "eventType" TEXT NOT NULL,
  "source" TEXT NOT NULL,
  "payload" JSONB NOT NULL DEFAULT '{}',
  "occurredAt" TIMESTAMP(3) NOT NULL,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

  CONSTRAINT "billing_events_pkey" PRIMARY KEY ("id")
);

ALTER TABLE "subscription_invoices"
  ADD COLUMN "billingInvoiceId" TEXT;

CREATE UNIQUE INDEX "subscription_invoices_billingInvoiceId_key" ON "subscription_invoices"("billingInvoiceId");
CREATE UNIQUE INDEX "billing_invoices_invoiceNumber_key" ON "billing_invoices"("invoiceNumber");
CREATE UNIQUE INDEX "billing_invoices_invoiceSequence_key" ON "billing_invoices"("invoiceSequence");
CREATE UNIQUE INDEX "billing_credit_balances_billingAccountId_currency_key" ON "billing_credit_balances"("billingAccountId", "currency");

CREATE INDEX "billing_accounts_companyId_idx" ON "billing_accounts"("companyId");
CREATE INDEX "billing_accounts_companyId_isPrimary_idx" ON "billing_accounts"("companyId", "isPrimary");
CREATE INDEX "billing_payment_methods_billingAccountId_idx" ON "billing_payment_methods"("billingAccountId");
CREATE INDEX "billing_invoices_billingAccountId_idx" ON "billing_invoices"("billingAccountId");
CREATE INDEX "billing_invoices_companyId_idx" ON "billing_invoices"("companyId");
CREATE INDEX "billing_invoices_subscriptionId_idx" ON "billing_invoices"("subscriptionId");
CREATE INDEX "billing_invoice_line_items_invoiceId_idx" ON "billing_invoice_line_items"("invoiceId");
CREATE INDEX "billing_payment_intents_invoiceId_idx" ON "billing_payment_intents"("invoiceId");
CREATE INDEX "billing_payment_intents_billingAccountId_idx" ON "billing_payment_intents"("billingAccountId");
CREATE INDEX "billing_payment_attempts_invoiceId_idx" ON "billing_payment_attempts"("invoiceId");
CREATE INDEX "billing_payment_attempts_billingAccountId_idx" ON "billing_payment_attempts"("billingAccountId");
CREATE INDEX "billing_credit_ledger_entries_billingAccountId_idx" ON "billing_credit_ledger_entries"("billingAccountId");
CREATE INDEX "billing_credit_notes_invoiceId_idx" ON "billing_credit_notes"("invoiceId");
CREATE INDEX "billing_credit_notes_billingAccountId_idx" ON "billing_credit_notes"("billingAccountId");
CREATE INDEX "billing_refunds_invoiceId_idx" ON "billing_refunds"("invoiceId");
CREATE INDEX "billing_refunds_billingAccountId_idx" ON "billing_refunds"("billingAccountId");
CREATE INDEX "billing_tax_records_invoiceId_idx" ON "billing_tax_records"("invoiceId");
CREATE INDEX "billing_events_billingAccountId_idx" ON "billing_events"("billingAccountId");
CREATE INDEX "billing_events_invoiceId_idx" ON "billing_events"("invoiceId");
CREATE INDEX "billing_events_subscriptionId_idx" ON "billing_events"("subscriptionId");
CREATE INDEX "billing_events_companyId_idx" ON "billing_events"("companyId");

ALTER TABLE "billing_accounts"
  ADD CONSTRAINT "billing_accounts_companyId_fkey"
  FOREIGN KEY ("companyId") REFERENCES "companies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_payment_methods"
  ADD CONSTRAINT "billing_payment_methods_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_accounts"
  ADD CONSTRAINT "billing_accounts_defaultPaymentMethodId_fkey"
  FOREIGN KEY ("defaultPaymentMethodId") REFERENCES "billing_payment_methods"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_invoices"
  ADD CONSTRAINT "billing_invoices_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_invoices"
  ADD CONSTRAINT "billing_invoices_companyId_fkey"
  FOREIGN KEY ("companyId") REFERENCES "companies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_invoices"
  ADD CONSTRAINT "billing_invoices_subscriptionId_fkey"
  FOREIGN KEY ("subscriptionId") REFERENCES "subscriptions"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "subscription_invoices"
  ADD CONSTRAINT "subscription_invoices_billingInvoiceId_fkey"
  FOREIGN KEY ("billingInvoiceId") REFERENCES "billing_invoices"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_invoice_line_items"
  ADD CONSTRAINT "billing_invoice_line_items_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_payment_intents"
  ADD CONSTRAINT "billing_payment_intents_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_payment_intents"
  ADD CONSTRAINT "billing_payment_intents_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_payment_intents"
  ADD CONSTRAINT "billing_payment_intents_paymentMethodId_fkey"
  FOREIGN KEY ("paymentMethodId") REFERENCES "billing_payment_methods"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_payment_attempts"
  ADD CONSTRAINT "billing_payment_attempts_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_payment_attempts"
  ADD CONSTRAINT "billing_payment_attempts_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_payment_attempts"
  ADD CONSTRAINT "billing_payment_attempts_paymentIntentId_fkey"
  FOREIGN KEY ("paymentIntentId") REFERENCES "billing_payment_intents"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_payment_attempts"
  ADD CONSTRAINT "billing_payment_attempts_paymentMethodId_fkey"
  FOREIGN KEY ("paymentMethodId") REFERENCES "billing_payment_methods"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_credit_balances"
  ADD CONSTRAINT "billing_credit_balances_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_credit_ledger_entries"
  ADD CONSTRAINT "billing_credit_ledger_entries_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_credit_ledger_entries"
  ADD CONSTRAINT "billing_credit_ledger_entries_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_credit_notes"
  ADD CONSTRAINT "billing_credit_notes_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_credit_notes"
  ADD CONSTRAINT "billing_credit_notes_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_refunds"
  ADD CONSTRAINT "billing_refunds_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_refunds"
  ADD CONSTRAINT "billing_refunds_paymentAttemptId_fkey"
  FOREIGN KEY ("paymentAttemptId") REFERENCES "billing_payment_attempts"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_refunds"
  ADD CONSTRAINT "billing_refunds_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_tax_records"
  ADD CONSTRAINT "billing_tax_records_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "billing_events"
  ADD CONSTRAINT "billing_events_billingAccountId_fkey"
  FOREIGN KEY ("billingAccountId") REFERENCES "billing_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_events"
  ADD CONSTRAINT "billing_events_invoiceId_fkey"
  FOREIGN KEY ("invoiceId") REFERENCES "billing_invoices"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_events"
  ADD CONSTRAINT "billing_events_subscriptionId_fkey"
  FOREIGN KEY ("subscriptionId") REFERENCES "subscriptions"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "billing_events"
  ADD CONSTRAINT "billing_events_companyId_fkey"
  FOREIGN KEY ("companyId") REFERENCES "companies"("id") ON DELETE SET NULL ON UPDATE CASCADE;

INSERT INTO "billing_accounts" (
  "id",
  "companyId",
  "isPrimary",
  "legalName",
  "billingEmail",
  "billingAddress",
  "taxExempt",
  "defaultCurrency",
  "invoiceTerms",
  "netTermsDays",
  "metadata"
)
SELECT
  'ba_' || c."id",
  c."id",
  true,
  c."name",
  c."email",
  c."address",
  false,
  COALESCE(a."currency", 'MAD'),
  'DUE_ON_RECEIPT'::"BillingInvoiceTerms",
  0,
  '{}'::jsonb
FROM "companies" c
LEFT JOIN "accounting_settings" a ON a."companyId" = c."id"
WHERE NOT EXISTS (
  SELECT 1
  FROM "billing_accounts" ba
  WHERE ba."companyId" = c."id" AND ba."isPrimary" = true
);
