CREATE TABLE IF NOT EXISTS qipai_order_shares (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  order_id BIGINT UNSIGNED NOT NULL,
  token_hash CHAR(64) NOT NULL,
  token_prefix VARCHAR(12) NOT NULL,
  allow_view_room TINYINT(1) NOT NULL DEFAULT 1,
  allow_open_door TINYINT(1) NOT NULL DEFAULT 1,
  allow_renew TINYINT(1) NOT NULL DEFAULT 0,
  expires_at DATETIME(3) NOT NULL,
  created_by BIGINT UNSIGNED NOT NULL,
  revoked_at DATETIME(3) NULL,
  revoked_by BIGINT UNSIGNED NULL,
  last_used_at DATETIME(3) NULL,
  use_count BIGINT UNSIGNED NOT NULL DEFAULT 0,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_qipai_order_share_tenant
    FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_order_share_order
    FOREIGN KEY (order_id) REFERENCES qipai_orders(id),
  CONSTRAINT fk_qipai_order_share_creator
    FOREIGN KEY (created_by) REFERENCES qipai_users(id),
  CONSTRAINT fk_qipai_order_share_revoker
    FOREIGN KEY (revoked_by) REFERENCES qipai_users(id),
  UNIQUE KEY uq_qipai_order_share_token_hash (token_hash),
  KEY idx_qipai_order_share_order (tenant_id, order_id, revoked_at, expires_at),
  KEY idx_qipai_order_share_expiry (expires_at, revoked_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026062014', 'm04d_order_shares');
