CREATE TABLE IF NOT EXISTS qipai_recharge_plans (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  store_id BIGINT UNSIGNED NULL,
  name VARCHAR(128) NOT NULL,
  pay_amount_cents INT UNSIGNED NOT NULL,
  gift_amount_cents INT UNSIGNED NOT NULL DEFAULT 0,
  scope_type VARCHAR(16) NOT NULL DEFAULT 'TENANT',
  starts_at DATETIME(3) NULL,
  ends_at DATETIME(3) NULL,
  purchase_limit_per_user INT UNSIGNED NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE',
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
    ON UPDATE CURRENT_TIMESTAMP(3),
  deleted_at DATETIME(3) NULL,
  CONSTRAINT fk_qipai_recharge_plan_tenant
    FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_recharge_plan_store
    FOREIGN KEY (store_id) REFERENCES qipai_stores(id),
  KEY idx_qipai_recharge_plan_scope (tenant_id, store_id, status, starts_at, ends_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS qipai_recharge_orders (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  user_id BIGINT UNSIGNED NOT NULL,
  store_id BIGINT UNSIGNED NULL,
  plan_id BIGINT UNSIGNED NOT NULL,
  payment_id BIGINT UNSIGNED NULL,
  recharge_no VARCHAR(64) NOT NULL,
  client_request_id VARCHAR(128) NOT NULL,
  pay_amount_cents INT UNSIGNED NOT NULL,
  gift_amount_cents INT UNSIGNED NOT NULL DEFAULT 0,
  status VARCHAR(32) NOT NULL DEFAULT 'PENDING_PAYMENT',
  paid_at DATETIME(3) NULL,
  credited_at DATETIME(3) NULL,
  trace_id VARCHAR(128) NOT NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
    ON UPDATE CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_qipai_recharge_order_tenant
    FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_recharge_order_user
    FOREIGN KEY (user_id) REFERENCES qipai_users(id),
  CONSTRAINT fk_qipai_recharge_order_store
    FOREIGN KEY (store_id) REFERENCES qipai_stores(id),
  CONSTRAINT fk_qipai_recharge_order_plan
    FOREIGN KEY (plan_id) REFERENCES qipai_recharge_plans(id),
  CONSTRAINT fk_qipai_recharge_order_payment
    FOREIGN KEY (payment_id) REFERENCES qipai_payments(id),
  UNIQUE KEY uq_qipai_recharge_order_no (tenant_id, recharge_no),
  UNIQUE KEY uq_qipai_recharge_order_request (tenant_id, user_id, client_request_id),
  KEY idx_qipai_recharge_order_user (tenant_id, user_id, status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026062422', 'm07b_recharge_plans');
