CREATE TABLE IF NOT EXISTS orders (
  id VARCHAR(36) NOT NULL,
  order_no VARCHAR(40) NOT NULL,
  user_id VARCHAR(36) NOT NULL,
  source_type VARCHAR(32) NOT NULL,
  provider VARCHAR(64) NULL,
  total_amount DECIMAL(10, 2) NOT NULL,
  payable_amount DECIMAL(10, 2) NOT NULL,
  paid_amount DECIMAL(10, 2) NOT NULL DEFAULT 0,
  payment_status VARCHAR(32) NOT NULL,
  fulfillment_status VARCHAR(32) NOT NULL,
  remark VARCHAR(500) NULL,
  paid_at DATETIME NULL,
  closed_at DATETIME NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  PRIMARY KEY (id),
  UNIQUE KEY uk_orders_order_no (order_no),
  KEY idx_orders_user_created (user_id, created_at),
  KEY idx_orders_status_created (payment_status, fulfillment_status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS order_items (
  id VARCHAR(36) NOT NULL,
  order_id VARCHAR(36) NOT NULL,
  product_id VARCHAR(36) NOT NULL,
  product_name VARCHAR(255) NOT NULL,
  source_type VARCHAR(32) NOT NULL,
  external_product_id VARCHAR(160) NULL,
  provider VARCHAR(64) NULL,
  unit_price DECIMAL(10, 2) NOT NULL,
  quantity INT NOT NULL DEFAULT 1,
  total_amount DECIMAL(10, 2) NOT NULL,
  payload JSON NULL,
  encrypted_payload JSON NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  PRIMARY KEY (id),
  KEY idx_order_items_order_id (order_id),
  KEY idx_order_items_product_id (product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS order_fulfillments (
  id VARCHAR(36) NOT NULL,
  order_id VARCHAR(36) NOT NULL,
  order_item_id VARCHAR(36) NOT NULL,
  fulfillment_type VARCHAR(40) NOT NULL,
  status VARCHAR(32) NOT NULL,
  provider VARCHAR(64) NULL,
  external_order_no VARCHAR(160) NULL,
  request_payload JSON NULL,
  response_payload JSON NULL,
  error_message VARCHAR(500) NULL,
  submitted_at DATETIME NULL,
  completed_at DATETIME NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  PRIMARY KEY (id),
  KEY idx_order_fulfillments_order_id (order_id),
  KEY idx_order_fulfillments_status (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
