import { Migration } from '../migrate.js'

export const up: Migration['up'] = async (db) => {
  // Tenants table - more flexible than Azure
  await db.query(`
    CREATE TABLE IF NOT EXISTS tenants (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      name VARCHAR(255) UNIQUE NOT NULL,
      domain VARCHAR(255) UNIQUE,
      billing_account_id VARCHAR(255) UNIQUE NOT NULL,
      status VARCHAR(50) NOT NULL DEFAULT 'PENDING_ACTIVATION' 
        CHECK (status IN ('ACTIVE', 'SUSPENDED', 'DELETED', 'PENDING_ACTIVATION')),
      tier VARCHAR(50) NOT NULL DEFAULT 'STANDARD' 
        CHECK (tier IN ('FREE', 'STANDARD', 'ENTERPRISE', 'SOVEREIGN')),
      metadata JSONB DEFAULT '{}'::jsonb,
      quota_limits JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Tenant users junction table with fine-grained permissions
  await db.query(`
    CREATE TABLE IF NOT EXISTS tenant_users (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
      role VARCHAR(50) NOT NULL DEFAULT 'TENANT_USER' 
        CHECK (role IN ('TENANT_OWNER', 'TENANT_ADMIN', 'TENANT_USER', 'TENANT_VIEWER', 'TENANT_BILLING_ADMIN')),
      permissions JSONB DEFAULT '{}'::jsonb,
      external_id VARCHAR(255),
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      UNIQUE(tenant_id, user_id)
    )
  `)

  // Add tenant_id to existing tables
  await db.query(`
    ALTER TABLE resources 
    ADD COLUMN IF NOT EXISTS tenant_id UUID REFERENCES tenants(id) ON DELETE SET NULL
  `)

  await db.query(`
    ALTER TABLE sites 
    ADD COLUMN IF NOT EXISTS tenant_id UUID REFERENCES tenants(id) ON DELETE SET NULL
  `)

  await db.query(`
    ALTER TABLE resource_inventory 
    ADD COLUMN IF NOT EXISTS tenant_id UUID REFERENCES tenants(id) ON DELETE SET NULL
  `)

  // Create indexes for tenant isolation
  await db.query(`CREATE INDEX IF NOT EXISTS idx_resources_tenant_id ON resources(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_sites_tenant_id ON sites(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_resource_inventory_tenant_id ON resource_inventory(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_tenant_users_tenant_id ON tenant_users(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_tenant_users_user_id ON tenant_users(user_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_tenants_domain ON tenants(domain) WHERE domain IS NOT NULL`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_tenants_billing_account_id ON tenants(billing_account_id)`)

  // Triggers for tenant_users
  await db.query(`
    CREATE TRIGGER update_tenant_users_updated_at BEFORE UPDATE ON tenant_users
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_tenants_updated_at BEFORE UPDATE ON tenants
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  // Billing tables - more detailed than Azure
  await db.query(`
    CREATE TABLE IF NOT EXISTS billing_accounts (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL UNIQUE REFERENCES tenants(id) ON DELETE CASCADE,
      account_name VARCHAR(255) NOT NULL,
      payment_methods JSONB DEFAULT '[]'::jsonb,
      currency VARCHAR(10) NOT NULL DEFAULT 'USD',
      billing_address JSONB,
      tax_id VARCHAR(255),
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Usage records with per-second granularity (vs Azure's hourly)
  await db.query(`
    CREATE TABLE IF NOT EXISTS usage_records (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      resource_id UUID REFERENCES resource_inventory(id) ON DELETE SET NULL,
      resource_type VARCHAR(100) NOT NULL,
      metric_type VARCHAR(100) NOT NULL,
      quantity NUMERIC NOT NULL,
      unit VARCHAR(50) NOT NULL,
      cost NUMERIC NOT NULL DEFAULT 0,
      currency VARCHAR(10) NOT NULL DEFAULT 'USD',
      timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
      labels JSONB DEFAULT '{}'::jsonb,
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Cost allocations - more flexible than Azure tags
  await db.query(`
    CREATE TABLE IF NOT EXISTS cost_allocations (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      usage_record_id UUID REFERENCES usage_records(id) ON DELETE CASCADE,
      allocation_key VARCHAR(255) NOT NULL,
      allocation_value VARCHAR(255) NOT NULL,
      percentage NUMERIC NOT NULL CHECK (percentage >= 0 AND percentage <= 100),
      cost NUMERIC NOT NULL,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Invoices with line-item details
  await db.query(`
    CREATE TABLE IF NOT EXISTS invoices (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      invoice_number VARCHAR(255) UNIQUE NOT NULL,
      billing_period_start TIMESTAMP WITH TIME ZONE NOT NULL,
      billing_period_end TIMESTAMP WITH TIME ZONE NOT NULL,
      subtotal NUMERIC NOT NULL,
      tax NUMERIC NOT NULL DEFAULT 0,
      total NUMERIC NOT NULL,
      currency VARCHAR(10) NOT NULL DEFAULT 'USD',
      status VARCHAR(50) NOT NULL DEFAULT 'DRAFT' 
        CHECK (status IN ('DRAFT', 'PENDING', 'PAID', 'OVERDUE', 'CANCELLED')),
      due_date TIMESTAMP WITH TIME ZONE,
      paid_at TIMESTAMP WITH TIME ZONE,
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Invoice line items
  await db.query(`
    CREATE TABLE IF NOT EXISTS invoice_line_items (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      invoice_id UUID NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,
      description TEXT NOT NULL,
      quantity NUMERIC NOT NULL,
      unit_price NUMERIC NOT NULL,
      total NUMERIC NOT NULL,
      resource_id UUID REFERENCES resource_inventory(id) ON DELETE SET NULL,
      usage_record_ids UUID[],
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Payments with multiple payment methods
  await db.query(`
    CREATE TABLE IF NOT EXISTS payments (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      invoice_id UUID REFERENCES invoices(id) ON DELETE SET NULL,
      amount NUMERIC NOT NULL,
      currency VARCHAR(10) NOT NULL DEFAULT 'USD',
      payment_method VARCHAR(50) NOT NULL,
      payment_method_details JSONB,
      status VARCHAR(50) NOT NULL DEFAULT 'PENDING' 
        CHECK (status IN ('PENDING', 'PROCESSING', 'COMPLETED', 'FAILED', 'REFUNDED')),
      transaction_id VARCHAR(255),
      processed_at TIMESTAMP WITH TIME ZONE,
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Billing alerts - more granular than Azure
  await db.query(`
    CREATE TABLE IF NOT EXISTS billing_alerts (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      name VARCHAR(255) NOT NULL,
      alert_type VARCHAR(50) NOT NULL 
        CHECK (alert_type IN ('BUDGET', 'THRESHOLD', 'ANOMALY', 'FORECAST')),
      threshold NUMERIC,
      budget_id UUID,
      condition JSONB NOT NULL,
      notification_channels JSONB DEFAULT '[]'::jsonb,
      enabled BOOLEAN NOT NULL DEFAULT true,
      last_triggered_at TIMESTAMP WITH TIME ZONE,
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Budgets
  await db.query(`
    CREATE TABLE IF NOT EXISTS budgets (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      name VARCHAR(255) NOT NULL,
      amount NUMERIC NOT NULL,
      currency VARCHAR(10) NOT NULL DEFAULT 'USD',
      period VARCHAR(50) NOT NULL 
        CHECK (period IN ('DAILY', 'WEEKLY', 'MONTHLY', 'QUARTERLY', 'YEARLY')),
      start_date TIMESTAMP WITH TIME ZONE NOT NULL,
      end_date TIMESTAMP WITH TIME ZONE,
      alert_thresholds JSONB DEFAULT '[]'::jsonb,
      filters JSONB DEFAULT '{}'::jsonb,
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Reserved capacity
  await db.query(`
    CREATE TABLE IF NOT EXISTS reserved_capacity (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
      resource_type VARCHAR(100) NOT NULL,
      quantity NUMERIC NOT NULL,
      unit VARCHAR(50) NOT NULL,
      start_date TIMESTAMP WITH TIME ZONE NOT NULL,
      end_date TIMESTAMP WITH TIME ZONE NOT NULL,
      upfront_cost NUMERIC,
      monthly_cost NUMERIC NOT NULL,
      currency VARCHAR(10) NOT NULL DEFAULT 'USD',
      status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE' 
        CHECK (status IN ('ACTIVE', 'EXPIRED', 'CANCELLED')),
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Discounts - custom discount rules per tenant
  await db.query(`
    CREATE TABLE IF NOT EXISTS discounts (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
      name VARCHAR(255) NOT NULL,
      discount_type VARCHAR(50) NOT NULL 
        CHECK (discount_type IN ('PERCENTAGE', 'FIXED_AMOUNT', 'VOLUME', 'TIER')),
      value NUMERIC NOT NULL,
      currency VARCHAR(10),
      conditions JSONB DEFAULT '{}'::jsonb,
      start_date TIMESTAMP WITH TIME ZONE NOT NULL,
      end_date TIMESTAMP WITH TIME ZONE,
      enabled BOOLEAN NOT NULL DEFAULT true,
      metadata JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    )
  `)

  // Indexes for billing tables
  await db.query(`CREATE INDEX IF NOT EXISTS idx_billing_accounts_tenant_id ON billing_accounts(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_usage_records_tenant_id ON usage_records(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_usage_records_timestamp ON usage_records(timestamp)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_usage_records_resource_id ON usage_records(resource_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_usage_records_tenant_timestamp ON usage_records(tenant_id, timestamp)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_cost_allocations_tenant_id ON cost_allocations(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_cost_allocations_usage_record_id ON cost_allocations(usage_record_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_invoices_tenant_id ON invoices(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_invoices_status ON invoices(status)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_invoices_billing_period ON invoices(billing_period_start, billing_period_end)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_invoice_line_items_invoice_id ON invoice_line_items(invoice_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_payments_tenant_id ON payments(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_payments_invoice_id ON payments(invoice_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_payments_status ON payments(status)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_billing_alerts_tenant_id ON billing_alerts(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_billing_alerts_enabled ON billing_alerts(enabled) WHERE enabled = true`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_budgets_tenant_id ON budgets(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_reserved_capacity_tenant_id ON reserved_capacity(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_reserved_capacity_status ON reserved_capacity(status)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_discounts_tenant_id ON discounts(tenant_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_discounts_enabled ON discounts(enabled) WHERE enabled = true`)

  // Triggers for billing tables
  await db.query(`
    CREATE TRIGGER update_billing_accounts_updated_at BEFORE UPDATE ON billing_accounts
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_invoices_updated_at BEFORE UPDATE ON invoices
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_payments_updated_at BEFORE UPDATE ON payments
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_billing_alerts_updated_at BEFORE UPDATE ON billing_alerts
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_budgets_updated_at BEFORE UPDATE ON budgets
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_reserved_capacity_updated_at BEFORE UPDATE ON reserved_capacity
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  await db.query(`
    CREATE TRIGGER update_discounts_updated_at BEFORE UPDATE ON discounts
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)

  // Row-level security policies for tenant isolation
  await db.query(`
    CREATE POLICY tenant_isolation_resources ON resources
    FOR ALL
    USING (
      tenant_id IS NULL OR 
      tenant_id IN (
        SELECT tenant_id FROM tenant_users 
        WHERE user_id = current_setting('app.current_user_id', true)::UUID
      ) OR
      EXISTS (
        SELECT 1 FROM users 
        WHERE id = current_setting('app.current_user_id', true)::UUID 
        AND role = 'ADMIN'
      )
    )
  `)

  await db.query(`
    CREATE POLICY tenant_isolation_sites ON sites
    FOR ALL
    USING (
      tenant_id IS NULL OR 
      tenant_id IN (
        SELECT tenant_id FROM tenant_users 
        WHERE user_id = current_setting('app.current_user_id', true)::UUID
      ) OR
      EXISTS (
        SELECT 1 FROM users 
        WHERE id = current_setting('app.current_user_id', true)::UUID 
        AND role = 'ADMIN'
      )
    )
  `)

  await db.query(`
    CREATE POLICY tenant_isolation_resource_inventory ON resource_inventory
    FOR ALL
    USING (
      tenant_id IS NULL OR 
      tenant_id IN (
        SELECT tenant_id FROM tenant_users 
        WHERE user_id = current_setting('app.current_user_id', true)::UUID
      ) OR
      EXISTS (
        SELECT 1 FROM users 
        WHERE id = current_setting('app.current_user_id', true)::UUID 
        AND role = 'ADMIN'
      )
    )
  `)
}

export const down: Migration['down'] = async (db) => {
  // Drop RLS policies
  await db.query(`DROP POLICY IF EXISTS tenant_isolation_resource_inventory ON resource_inventory`)
  await db.query(`DROP POLICY IF EXISTS tenant_isolation_sites ON sites`)
  await db.query(`DROP POLICY IF EXISTS tenant_isolation_resources ON resources`)

  // Drop triggers
  await db.query(`DROP TRIGGER IF EXISTS update_discounts_updated_at ON discounts`)
  await db.query(`DROP TRIGGER IF EXISTS update_reserved_capacity_updated_at ON reserved_capacity`)
  await db.query(`DROP TRIGGER IF EXISTS update_budgets_updated_at ON budgets`)
  await db.query(`DROP TRIGGER IF EXISTS update_billing_alerts_updated_at ON billing_alerts`)
  await db.query(`DROP TRIGGER IF EXISTS update_payments_updated_at ON payments`)
  await db.query(`DROP TRIGGER IF EXISTS update_invoices_updated_at ON invoices`)
  await db.query(`DROP TRIGGER IF EXISTS update_billing_accounts_updated_at ON billing_accounts`)
  await db.query(`DROP TRIGGER IF EXISTS update_tenants_updated_at ON tenants`)
  await db.query(`DROP TRIGGER IF EXISTS update_tenant_users_updated_at ON tenant_users`)

  // Drop indexes
  await db.query(`DROP INDEX IF EXISTS idx_discounts_enabled`)
  await db.query(`DROP INDEX IF EXISTS idx_discounts_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_reserved_capacity_status`)
  await db.query(`DROP INDEX IF EXISTS idx_reserved_capacity_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_budgets_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_billing_alerts_enabled`)
  await db.query(`DROP INDEX IF EXISTS idx_billing_alerts_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_payments_status`)
  await db.query(`DROP INDEX IF EXISTS idx_payments_invoice_id`)
  await db.query(`DROP INDEX IF EXISTS idx_payments_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_invoice_line_items_invoice_id`)
  await db.query(`DROP INDEX IF EXISTS idx_invoices_billing_period`)
  await db.query(`DROP INDEX IF EXISTS idx_invoices_status`)
  await db.query(`DROP INDEX IF EXISTS idx_invoices_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_cost_allocations_usage_record_id`)
  await db.query(`DROP INDEX IF EXISTS idx_cost_allocations_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_usage_records_tenant_timestamp`)
  await db.query(`DROP INDEX IF EXISTS idx_usage_records_resource_id`)
  await db.query(`DROP INDEX IF EXISTS idx_usage_records_timestamp`)
  await db.query(`DROP INDEX IF EXISTS idx_usage_records_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_billing_accounts_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_tenants_billing_account_id`)
  await db.query(`DROP INDEX IF EXISTS idx_tenants_domain`)
  await db.query(`DROP INDEX IF EXISTS idx_tenant_users_user_id`)
  await db.query(`DROP INDEX IF EXISTS idx_tenant_users_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_resource_inventory_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_sites_tenant_id`)
  await db.query(`DROP INDEX IF EXISTS idx_resources_tenant_id`)

  // Drop tables
  await db.query(`DROP TABLE IF EXISTS discounts`)
  await db.query(`DROP TABLE IF EXISTS reserved_capacity`)
  await db.query(`DROP TABLE IF EXISTS budgets`)
  await db.query(`DROP TABLE IF EXISTS billing_alerts`)
  await db.query(`DROP TABLE IF EXISTS payments`)
  await db.query(`DROP TABLE IF EXISTS invoice_line_items`)
  await db.query(`DROP TABLE IF EXISTS invoices`)
  await db.query(`DROP TABLE IF EXISTS cost_allocations`)
  await db.query(`DROP TABLE IF EXISTS usage_records`)
  await db.query(`DROP TABLE IF EXISTS billing_accounts`)

  // Remove tenant_id columns
  await db.query(`ALTER TABLE resource_inventory DROP COLUMN IF EXISTS tenant_id`)
  await db.query(`ALTER TABLE sites DROP COLUMN IF EXISTS tenant_id`)
  await db.query(`ALTER TABLE resources DROP COLUMN IF EXISTS tenant_id`)

  // Drop tenant tables
  await db.query(`DROP TABLE IF EXISTS tenant_users`)
  await db.query(`DROP TABLE IF EXISTS tenants`)
}

