-- =====================================================
-- PORTFOLIO SCHEMA - PORTFOLIO SNAPSHOTS TABLE
-- =====================================================
-- Description: Daily snapshots of portfolio values for performance tracking
-- Schema: portfolio
-- Author: Database Agent
-- Date: 2026-01-25
-- =====================================================

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

  -- Values at snapshot time
  total_value DECIMAL(20, 8) NOT NULL,
  total_cost DECIMAL(20, 8) NOT NULL,
  unrealized_pnl DECIMAL(20, 8) NOT NULL,
  unrealized_pnl_percent DECIMAL(10, 4) NOT NULL,

  -- Daily changes
  day_change DECIMAL(20, 8) NOT NULL DEFAULT 0,
  day_change_percent DECIMAL(10, 4) NOT NULL DEFAULT 0,

  -- Allocation snapshot (JSON for flexibility)
  allocations JSONB,

  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_portfolio_snapshots_portfolio_id ON portfolio.portfolio_snapshots(portfolio_id);
CREATE INDEX idx_portfolio_snapshots_date ON portfolio.portfolio_snapshots(snapshot_date);

-- One snapshot per portfolio per day
CREATE UNIQUE INDEX idx_portfolio_snapshots_unique_day
  ON portfolio.portfolio_snapshots(portfolio_id, snapshot_date);

-- Comments
COMMENT ON TABLE portfolio.portfolio_snapshots IS 'Daily snapshots for historical performance tracking';
COMMENT ON COLUMN portfolio.portfolio_snapshots.allocations IS 'JSON snapshot of allocation state at that time';
