-- =====================================================
-- INVESTMENT SCHEMA - TRANSACTIONS TABLE
-- =====================================================
-- Description: Deposits, withdrawals, and distributions
-- Schema: investment
-- Author: Database Agent
-- Date: 2025-12-06
-- =====================================================

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

  -- Cuenta asociada
  account_id UUID NOT NULL REFERENCES investment.accounts(id) ON DELETE CASCADE,

  -- Identificación
  transaction_number VARCHAR(30) NOT NULL UNIQUE, -- TXN-202512-00001

  -- Tipo y monto
  transaction_type investment.transaction_type NOT NULL,
  amount DECIMAL(15,2) NOT NULL CHECK (amount > 0),

  -- Estado
  status investment.transaction_status DEFAULT 'pending',

  -- Detalles de pago (para deposits/withdrawals)
  payment_method VARCHAR(50), -- bank_transfer, card, crypto
  payment_reference VARCHAR(100),
  payment_metadata JSONB,

  -- Distribución (para transaction_type = 'distribution')
  distribution_id UUID REFERENCES investment.distributions(id),

  -- Balance después de transacción
  balance_before DECIMAL(15,2),
  balance_after DECIMAL(15,2),

  -- Procesamiento
  requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  processed_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  failed_at TIMESTAMPTZ,
  failure_reason TEXT,

  -- Aprobación (para withdrawals)
  requires_approval BOOLEAN DEFAULT false,
  approved_by VARCHAR(100),
  approved_at TIMESTAMPTZ,

  -- Metadata
  notes TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Índices
CREATE INDEX idx_transactions_account ON investment.transactions(account_id);
CREATE INDEX idx_transactions_type ON investment.transactions(transaction_type);
CREATE INDEX idx_transactions_status ON investment.transactions(status);
CREATE INDEX idx_transactions_number ON investment.transactions(transaction_number);
CREATE INDEX idx_transactions_distribution ON investment.transactions(distribution_id);
CREATE INDEX idx_transactions_requested ON investment.transactions(requested_at DESC);

-- Comentarios
COMMENT ON TABLE investment.transactions IS 'All account transactions: deposits, withdrawals, and distributions';
COMMENT ON COLUMN investment.transactions.transaction_number IS 'Unique transaction identifier (TXN-YYYYMM-NNNNN)';
COMMENT ON COLUMN investment.transactions.payment_method IS 'Payment method for deposits/withdrawals';
COMMENT ON COLUMN investment.transactions.distribution_id IS 'Link to distribution record if transaction_type is distribution';
COMMENT ON COLUMN investment.transactions.requires_approval IS 'Whether withdrawal requires manual approval';
