-- Migration 003: Add server management tables
-- Purpose: Cloud server order tracking
-- Date: 2026-01-23
-- Reference: CLAUDE.md "Server Management System"
--
-- Background:
--   Telegram 봇을 통해 클라우드 서버 주문 내역을 기록하고 관리합니다.
--   예치금 시스템과 통합하여 자동 결제를 지원합니다.
--   서버 사양(cloud_providers, instance_specs)은 별도 외부 시스템에서 관리합니다.

-- Step 1: Create server_orders table (order lifecycle tracking)
CREATE TABLE IF NOT EXISTS server_orders (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id INTEGER NOT NULL,
  spec_id INTEGER NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'provisioning', 'active', 'failed', 'cancelled', 'terminated')),
  region TEXT NOT NULL,
  provider_instance_id TEXT,
  ip_address TEXT,
  root_password TEXT,
  price_paid INTEGER NOT NULL,
  error_message TEXT,
  provisioned_at DATETIME,
  terminated_at DATETIME,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id)
);

-- Step 2: Create user_servers table (ownership mapping)
CREATE TABLE IF NOT EXISTS user_servers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id INTEGER NOT NULL,
  order_id INTEGER UNIQUE NOT NULL,
  provider_id INTEGER NOT NULL,
  label TEXT,
  verified INTEGER DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id),
  FOREIGN KEY (order_id) REFERENCES server_orders(id)
);

-- Step 3: Create indexes for efficient queries
CREATE INDEX IF NOT EXISTS idx_server_orders_user ON server_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_server_orders_status ON server_orders(status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_user_servers_user ON user_servers(user_id);
CREATE INDEX IF NOT EXISTS idx_user_servers_provider ON user_servers(provider_id);

-- Verification Queries (주석으로 제공)
-- SELECT * FROM server_orders WHERE user_id = 1 ORDER BY created_at DESC;
-- SELECT * FROM user_servers WHERE user_id = 1;
