CREATE TABLE IF NOT EXISTS tenant_billing (
  tenant_id INT PRIMARY KEY,
  plan_code VARCHAR(30) NOT NULL DEFAULT 'free',
  subscription_status VARCHAR(30) NOT NULL DEFAULT 'active',
  stripe_customer_id VARCHAR(255) NULL,
  stripe_subscription_id VARCHAR(255) NULL,
  current_period_end DATETIME NULL,
  dolibarr_thirdparty_id VARCHAR(50) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_tenant_billing_plan (plan_code),
  CONSTRAINT fk_tenant_billing_tenant
    FOREIGN KEY (tenant_id) REFERENCES tenants(id)
    ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Alle bestehenden Mandanten starten auf dem freien Tarif; die tatsaechlich
-- erforderliche Stufe wird zur Laufzeit anhand der aktiven Teilnehmerzahl
-- berechnet (siehe app/billing.php), nicht fest hier eingetragen.
INSERT INTO tenant_billing (tenant_id, plan_code, subscription_status)
SELECT id, 'free', 'active' FROM tenants;
