-- Payment order tracking for PayPal transactions

CREATE TABLE IF NOT EXISTS payment_orders (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    order_id VARCHAR(255) UNIQUE NOT NULL,  -- PayPal order ID
    module_id UUID REFERENCES modules(id) ON DELETE SET NULL,  -- For module purchases
    webstore_subscription_id UUID REFERENCES licenses(id) ON DELETE SET NULL,  -- For Phase 5
    license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
    amount DECIMAL(10,2) NOT NULL,
    currency VARCHAR(3) DEFAULT 'USD',
    status VARCHAR(50) NOT NULL,  -- 'pending', 'completed', 'failed', 'refunded'
    transaction_id VARCHAR(255),  -- PayPal transaction/capture ID
    payer_email VARCHAR(255),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    completed_at TIMESTAMPTZ,
    metadata JSONB  -- Additional payment details
);

CREATE INDEX idx_payment_orders_license ON payment_orders(license_id);
CREATE INDEX idx_payment_orders_status ON payment_orders(status);
CREATE INDEX idx_payment_orders_order_id ON payment_orders(order_id);

COMMENT ON TABLE payment_orders IS 'PayPal payment tracking for module purchases and webstore subscriptions';
