-- =====================================================
-- PORTFOLIO SCHEMA - REBALANCE HISTORY TABLE
-- =====================================================
-- Description: History of portfolio rebalancing operations
-- Schema: portfolio
-- Author: Database Agent
-- Date: 2026-01-25
-- =====================================================

CREATE TABLE portfolio.rebalance_history (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  portfolio_id UUID NOT NULL REFERENCES portfolio.portfolios(id) ON DELETE CASCADE,

  -- Rebalance details
  asset VARCHAR(20) NOT NULL,
  action portfolio.rebalance_action NOT NULL,
  target_percent DECIMAL(5, 2) NOT NULL,
  actual_percent_before DECIMAL(5, 2) NOT NULL,
  actual_percent_after DECIMAL(5, 2) NOT NULL,

  -- Amounts
  quantity_change DECIMAL(20, 8) NOT NULL,
  value_change DECIMAL(20, 8) NOT NULL,
  price_at_rebalance DECIMAL(20, 8) NOT NULL,

  -- Execution
  executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  execution_status VARCHAR(20) NOT NULL DEFAULT 'completed',
  execution_notes TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_rebalance_history_portfolio_id ON portfolio.rebalance_history(portfolio_id);
CREATE INDEX idx_rebalance_history_executed_at ON portfolio.rebalance_history(executed_at);
CREATE INDEX idx_rebalance_history_asset ON portfolio.rebalance_history(asset);

-- Comments
COMMENT ON TABLE portfolio.rebalance_history IS 'Historical record of portfolio rebalancing operations';
COMMENT ON COLUMN portfolio.rebalance_history.action IS 'Type of rebalance action: buy, sell, hold';
COMMENT ON COLUMN portfolio.rebalance_history.quantity_change IS 'Amount of asset bought (+) or sold (-)';
COMMENT ON COLUMN portfolio.rebalance_history.value_change IS 'USD value of the transaction';
