-- =====================================================
-- INVESTMENT SCHEMA - DISTRIBUTIONS TABLE
-- =====================================================
-- Description: Profit distributions (80/20 split)
-- Schema: investment
-- Author: Database Agent
-- Date: 2025-12-06
-- =====================================================

CREATE TABLE investment.distributions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Producto PAMM
  product_id UUID NOT NULL REFERENCES investment.products(id) ON DELETE RESTRICT,

  -- Periodo
  period_start TIMESTAMPTZ NOT NULL,
  period_end TIMESTAMPTZ NOT NULL,
  period_label VARCHAR(20) NOT NULL, -- 2025-12, 2025-Q4

  -- Performance del agente de trading
  total_profit_amount DECIMAL(15,2) NOT NULL, -- Ganancia total generada
  total_profit_percent DECIMAL(10,4) NOT NULL, -- % de retorno

  -- Distribución 80/20
  investor_total_amount DECIMAL(15,2) NOT NULL, -- 80% para inversores
  platform_total_amount DECIMAL(15,2) NOT NULL, -- 20% para plataforma

  -- Cuentas participantes
  participating_accounts INTEGER NOT NULL,
  total_aum_at_period_start DECIMAL(15,2) NOT NULL,
  total_aum_at_period_end DECIMAL(15,2) NOT NULL,

  -- Estado
  status VARCHAR(20) DEFAULT 'pending', -- pending, processing, completed, failed

  -- Procesamiento
  calculated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  approved_by VARCHAR(100),
  approved_at TIMESTAMPTZ,
  distributed_at TIMESTAMPTZ,

  -- Metadata
  notes TEXT,
  distribution_metadata JSONB, -- Detalles adicionales

  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Validación
  CONSTRAINT valid_period CHECK (period_end > period_start),
  CONSTRAINT valid_split CHECK (
    investor_total_amount + platform_total_amount = total_profit_amount
  )
);

-- Índices
CREATE INDEX idx_distributions_product ON investment.distributions(product_id);
CREATE INDEX idx_distributions_period ON investment.distributions(period_start, period_end);
CREATE INDEX idx_distributions_status ON investment.distributions(status);
CREATE UNIQUE INDEX idx_distributions_product_period ON investment.distributions(product_id, period_label);

-- Comentarios
COMMENT ON TABLE investment.distributions IS 'Periodic profit distributions with 80/20 split';
COMMENT ON COLUMN investment.distributions.period_label IS 'Human-readable period identifier (YYYY-MM or YYYY-QN)';
COMMENT ON COLUMN investment.distributions.total_profit_amount IS 'Total profit generated by trading agent during period';
COMMENT ON COLUMN investment.distributions.investor_total_amount IS '80% of total profit distributed to all investors';
COMMENT ON COLUMN investment.distributions.platform_total_amount IS '20% of total profit retained by platform';
COMMENT ON COLUMN investment.distributions.total_aum_at_period_start IS 'Total Assets Under Management at period start';
