# ==============================================================================
# DDL Complete Matrix - Trading Platform
# Generated: 2026-01-27
# Total Schemas: 10
# Total Tables: 89
# ==============================================================================
version: "1.0.0"
project: "trading-platform"
generated_at: "2026-01-27T12:00:00Z"
database: "trading_platform"
user: "trading_user"

summary:
  total_schemas: 10
  total_tables: 89
  total_enums: 65
  total_functions: 7
  total_triggers: 2

schemas:
  audit:
    description: "Sistema de auditoría y logs"
    enums:
      - audit.event_type
      - audit.severity_level
      - audit.log_status
    tables:
      - name: audit_logs
        file: "01-audit_logs.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - event_type audit.event_type
          - table_name VARCHAR(100)
          - record_id UUID
          - changes JSONB
          - ip_address INET
          - user_agent TEXT
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_audit_logs_user
          - idx_audit_logs_event
          - idx_audit_logs_table
          - idx_audit_logs_created

      - name: security_events
        file: "02-security_events.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - event_type VARCHAR(50)
          - severity audit.severity_level
          - ip_address INET
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_security_events_user
          - idx_security_events_severity
          - idx_security_events_created

      - name: system_events
        file: "03-system_events.sql"
        columns:
          - id UUID PRIMARY KEY
          - event_type VARCHAR(100)
          - service_name VARCHAR(50)
          - severity audit.severity_level
          - message TEXT
          - metadata JSONB
          - created_at TIMESTAMPTZ
        indexes:
          - idx_system_events_service
          - idx_system_events_severity
          - idx_system_events_created

      - name: trading_audit
        file: "04-trading_audit.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - bot_id UUID REFERENCES trading.bots
          - order_id UUID REFERENCES trading.orders
          - action VARCHAR(50)
          - details JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: trading.bots
          - references: trading.orders
        indexes:
          - idx_trading_audit_user
          - idx_trading_audit_bot
          - idx_trading_audit_order
          - idx_trading_audit_created

      - name: api_request_logs
        file: "05-api_request_logs.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - endpoint VARCHAR(255)
          - method VARCHAR(10)
          - status_code INTEGER
          - response_time_ms INTEGER
          - ip_address INET
          - user_agent TEXT
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_api_logs_user
          - idx_api_logs_endpoint
          - idx_api_logs_status
          - idx_api_logs_created

      - name: data_access_logs
        file: "06-data_access_logs.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - table_name VARCHAR(100)
          - operation VARCHAR(20)
          - record_id UUID
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_data_access_user
          - idx_data_access_table
          - idx_data_access_created

      - name: compliance_logs
        file: "07-compliance_logs.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - compliance_type VARCHAR(50)
          - status audit.log_status
          - details JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_compliance_user
          - idx_compliance_type
          - idx_compliance_status
          - idx_compliance_created

    functions: []
    triggers: []

  auth:
    description: "Autenticación y autorización"
    enums:
      - auth.user_status
      - auth.user_role
      - auth.oauth_provider
      - auth.phone_channel
      - auth.auth_event_type
      - auth.mfa_method
    tables:
      - name: users
        file: "01-users.sql"
        columns:
          - id UUID PRIMARY KEY
          - email CITEXT UNIQUE
          - email_verified BOOLEAN
          - email_verified_at TIMESTAMPTZ
          - password_hash VARCHAR(255)
          - status auth.user_status
          - role auth.user_role
          - mfa_enabled BOOLEAN
          - mfa_method auth.mfa_method
          - mfa_secret VARCHAR(255)
          - phone_number VARCHAR(20)
          - phone_verified BOOLEAN
          - last_login_at TIMESTAMPTZ
          - last_login_ip INET
          - failed_login_attempts INTEGER
          - locked_until TIMESTAMPTZ
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys: []
        indexes:
          - idx_users_email
          - idx_users_status
          - idx_users_role
          - idx_users_last_login
          - idx_users_created_at

      - name: user_profiles
        file: "02-user_profiles.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - first_name VARCHAR(100)
          - last_name VARCHAR(100)
          - avatar_url TEXT
          - timezone VARCHAR(50)
          - language VARCHAR(10)
          - country VARCHAR(2)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_user_profiles_user_id

      - name: oauth_accounts
        file: "03-oauth_accounts.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - provider auth.oauth_provider
          - provider_account_id VARCHAR(255)
          - access_token TEXT
          - refresh_token TEXT
          - token_expires_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_oauth_user
          - idx_oauth_provider

      - name: sessions
        file: "04-sessions.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - token VARCHAR(255) UNIQUE
          - refresh_token VARCHAR(255)
          - ip_address INET
          - user_agent TEXT
          - expires_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_sessions_user
          - idx_sessions_token
          - idx_sessions_expires

      - name: email_verifications
        file: "05-email_verifications.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - token VARCHAR(255) UNIQUE
          - expires_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_email_verifications_user
          - idx_email_verifications_token

      - name: phone_verifications
        file: "06-phone_verifications.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - phone_number VARCHAR(20)
          - code VARCHAR(6)
          - channel auth.phone_channel
          - expires_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_phone_verifications_user
          - idx_phone_verifications_phone

      - name: password_reset_tokens
        file: "07-password_reset_tokens.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - token VARCHAR(255) UNIQUE
          - expires_at TIMESTAMPTZ
          - used_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_password_reset_user
          - idx_password_reset_token

      - name: auth_logs
        file: "08-auth_logs.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - event_type auth.auth_event_type
          - ip_address INET
          - user_agent TEXT
          - success BOOLEAN
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_auth_logs_user
          - idx_auth_logs_event
          - idx_auth_logs_created

      - name: login_attempts
        file: "09-login_attempts.sql"
        columns:
          - id UUID PRIMARY KEY
          - email CITEXT
          - ip_address INET
          - success BOOLEAN
          - failure_reason VARCHAR(100)
          - created_at TIMESTAMPTZ
        indexes:
          - idx_login_attempts_email
          - idx_login_attempts_ip
          - idx_login_attempts_created

      - name: rate_limiting_config
        file: "10-rate_limiting_config.sql"
        columns:
          - id UUID PRIMARY KEY
          - endpoint VARCHAR(255)
          - max_requests INTEGER
          - window_seconds INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        indexes:
          - idx_rate_limiting_endpoint

      - name: notifications
        file: "11-notifications.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - type VARCHAR(50)
          - title VARCHAR(255)
          - message TEXT
          - read BOOLEAN
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_notifications_user
          - idx_notifications_read
          - idx_notifications_created

      - name: user_push_tokens
        file: "12-user_push_tokens.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - platform VARCHAR(20)
          - token TEXT UNIQUE
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_user_push_tokens_user
          - idx_user_push_tokens_token

    functions:
      - name: update_updated_at
        file: "01-update_updated_at.sql"
      - name: log_auth_event
        file: "02-log_auth_event.sql"
      - name: cleanup_expired_sessions
        file: "03-cleanup_expired_sessions.sql"
      - name: create_user_profile_trigger
        file: "04-create_user_profile_trigger.sql"

    triggers:
      - trigger_users_updated_at
      - trigger_create_user_profile

  education:
    description: "Sistema educativo y gamification"
    enums:
      - education.difficulty_level
      - education.course_status
      - education.enrollment_status
      - education.lesson_content_type
      - education.question_type
      - education.achievement_type
    tables:
      - name: categories
        file: "01-categories.sql"
        columns:
          - id UUID PRIMARY KEY
          - name VARCHAR(100) UNIQUE
          - slug VARCHAR(100) UNIQUE
          - description TEXT
          - icon VARCHAR(50)
          - sort_order INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        indexes:
          - idx_categories_slug
          - idx_categories_sort_order

      - name: courses
        file: "02-courses.sql"
        columns:
          - id UUID PRIMARY KEY
          - category_id UUID REFERENCES education.categories
          - title VARCHAR(255)
          - slug VARCHAR(255) UNIQUE
          - description TEXT
          - difficulty education.difficulty_level
          - status education.course_status
          - thumbnail_url TEXT
          - estimated_hours INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: education.categories
        indexes:
          - idx_courses_category
          - idx_courses_slug
          - idx_courses_status

      - name: modules
        file: "03-modules.sql"
        columns:
          - id UUID PRIMARY KEY
          - course_id UUID REFERENCES education.courses
          - title VARCHAR(255)
          - description TEXT
          - sort_order INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: education.courses
        indexes:
          - idx_modules_course
          - idx_modules_sort_order

      - name: lessons
        file: "04-lessons.sql"
        columns:
          - id UUID PRIMARY KEY
          - module_id UUID REFERENCES education.modules
          - title VARCHAR(255)
          - content TEXT
          - content_type education.lesson_content_type
          - video_url TEXT
          - duration_minutes INTEGER
          - sort_order INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: education.modules
        indexes:
          - idx_lessons_module
          - idx_lessons_sort_order

      - name: enrollments
        file: "05-enrollments.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - course_id UUID REFERENCES education.courses
          - status education.enrollment_status
          - enrolled_at TIMESTAMPTZ
          - completed_at TIMESTAMPTZ
          - expires_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: education.courses
        indexes:
          - idx_enrollments_user
          - idx_enrollments_course
          - idx_enrollments_status

      - name: progress
        file: "06-progress.sql"
        columns:
          - id UUID PRIMARY KEY
          - enrollment_id UUID REFERENCES education.enrollments
          - lesson_id UUID REFERENCES education.lessons
          - completed BOOLEAN
          - completed_at TIMESTAMPTZ
          - time_spent_seconds INTEGER
        foreign_keys:
          - references: education.enrollments
          - references: education.lessons
        indexes:
          - idx_progress_enrollment
          - idx_progress_lesson

      - name: quizzes
        file: "07-quizzes.sql"
        columns:
          - id UUID PRIMARY KEY
          - lesson_id UUID REFERENCES education.lessons
          - title VARCHAR(255)
          - description TEXT
          - passing_score INTEGER
          - time_limit_minutes INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: education.lessons
        indexes:
          - idx_quizzes_lesson

      - name: quiz_questions
        file: "08-quiz_questions.sql"
        columns:
          - id UUID PRIMARY KEY
          - quiz_id UUID REFERENCES education.quizzes
          - question_type education.question_type
          - question TEXT
          - options JSONB
          - correct_answer JSONB
          - explanation TEXT
          - points INTEGER
          - sort_order INTEGER
        foreign_keys:
          - references: education.quizzes
        indexes:
          - idx_quiz_questions_quiz

      - name: quiz_attempts
        file: "09-quiz_attempts.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - quiz_id UUID REFERENCES education.quizzes
          - score INTEGER
          - max_score INTEGER
          - passed BOOLEAN
          - answers JSONB
          - started_at TIMESTAMPTZ
          - completed_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: education.quizzes
        indexes:
          - idx_quiz_attempts_user
          - idx_quiz_attempts_quiz

      - name: certificates
        file: "10-certificates.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - course_id UUID REFERENCES education.courses
          - certificate_number VARCHAR(50) UNIQUE
          - issued_at TIMESTAMPTZ
          - pdf_url TEXT
        foreign_keys:
          - references: auth.users
          - references: education.courses
        indexes:
          - idx_certificates_user
          - idx_certificates_course
          - idx_certificates_number

      - name: user_achievements
        file: "11-user_achievements.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - achievement_type education.achievement_type
          - title VARCHAR(255)
          - description TEXT
          - icon VARCHAR(50)
          - earned_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_user_achievements_user
          - idx_user_achievements_type

      - name: user_gamification_profile
        file: "12-user_gamification_profile.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users UNIQUE
          - level INTEGER
          - experience_points INTEGER
          - current_streak INTEGER
          - longest_streak INTEGER
          - total_courses_completed INTEGER
          - total_quizzes_passed INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_gamification_user
          - idx_gamification_level

      - name: user_activity_log
        file: "13-user_activity_log.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - activity_type VARCHAR(50)
          - xp_earned INTEGER
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_activity_log_user
          - idx_activity_log_type
          - idx_activity_log_created

      - name: course_reviews
        file: "14-course_reviews.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - course_id UUID REFERENCES education.courses
          - rating INTEGER
          - review TEXT
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: education.courses
        indexes:
          - idx_course_reviews_user
          - idx_course_reviews_course
          - idx_course_reviews_rating

      - name: videos
        file: "15-videos.sql"
        columns:
          - id UUID PRIMARY KEY
          - lesson_id UUID REFERENCES education.lessons
          - title VARCHAR(255)
          - url TEXT
          - thumbnail_url TEXT
          - duration_seconds INTEGER
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: education.lessons
        indexes:
          - idx_videos_lesson

    functions: []
    triggers: []

  financial:
    description: "Sistema financiero, wallets y pagos"
    enums:
      - financial.wallet_type
      - financial.wallet_status
      - financial.transaction_type
      - financial.transaction_status
      - financial.subscription_plan
      - financial.subscription_status
      - financial.currency_code
      - financial.payment_method
      - financial.payment_status
      - financial.invoice_type
      - financial.invoice_status
      - financial.audit_action
    tables:
      - name: wallets
        file: "01-wallets.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - wallet_type financial.wallet_type
          - status financial.wallet_status
          - balance DECIMAL(20,8)
          - available_balance DECIMAL(20,8)
          - pending_balance DECIMAL(20,8)
          - currency financial.currency_code
          - stripe_account_id VARCHAR(255)
          - stripe_customer_id VARCHAR(255)
          - daily_withdrawal_limit DECIMAL(15,2)
          - monthly_withdrawal_limit DECIMAL(15,2)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_wallets_user_id
          - idx_wallets_wallet_type
          - idx_wallets_status
          - idx_wallets_currency

      - name: wallet_transactions
        file: "02-wallet_transactions.sql"
        columns:
          - id UUID PRIMARY KEY
          - wallet_id UUID REFERENCES financial.wallets
          - transaction_type financial.transaction_type
          - amount DECIMAL(20,8)
          - balance_after DECIMAL(20,8)
          - status financial.transaction_status
          - reference_id UUID
          - metadata JSONB
          - created_at TIMESTAMPTZ
          - completed_at TIMESTAMPTZ
        foreign_keys:
          - references: financial.wallets
        indexes:
          - idx_wallet_transactions_wallet
          - idx_wallet_transactions_type
          - idx_wallet_transactions_status
          - idx_wallet_transactions_created

      - name: subscriptions
        file: "03-subscriptions.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - plan financial.subscription_plan
          - status financial.subscription_status
          - stripe_subscription_id VARCHAR(255)
          - current_period_start TIMESTAMPTZ
          - current_period_end TIMESTAMPTZ
          - cancel_at_period_end BOOLEAN
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_subscriptions_user
          - idx_subscriptions_status
          - idx_subscriptions_stripe_id

      - name: invoices
        file: "04-invoices.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - subscription_id UUID REFERENCES financial.subscriptions
          - invoice_type financial.invoice_type
          - status financial.invoice_status
          - amount DECIMAL(15,2)
          - currency financial.currency_code
          - stripe_invoice_id VARCHAR(255)
          - due_date TIMESTAMPTZ
          - paid_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: financial.subscriptions
        indexes:
          - idx_invoices_user
          - idx_invoices_subscription
          - idx_invoices_status
          - idx_invoices_stripe_id

      - name: payments
        file: "05-payments.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - invoice_id UUID REFERENCES financial.invoices
          - amount DECIMAL(15,2)
          - currency financial.currency_code
          - payment_method financial.payment_method
          - status financial.payment_status
          - stripe_payment_id VARCHAR(255)
          - metadata JSONB
          - created_at TIMESTAMPTZ
          - completed_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: financial.invoices
        indexes:
          - idx_payments_user
          - idx_payments_invoice
          - idx_payments_status
          - idx_payments_stripe_id

      - name: wallet_audit_log
        file: "06-wallet_audit_log.sql"
        columns:
          - id UUID PRIMARY KEY
          - wallet_id UUID REFERENCES financial.wallets
          - action financial.audit_action
          - old_values JSONB
          - new_values JSONB
          - performed_by UUID REFERENCES auth.users
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: financial.wallets
          - references: auth.users
        indexes:
          - idx_wallet_audit_wallet
          - idx_wallet_audit_action
          - idx_wallet_audit_created

      - name: currency_exchange_rates
        file: "07-currency_exchange_rates.sql"
        columns:
          - id UUID PRIMARY KEY
          - from_currency financial.currency_code
          - to_currency financial.currency_code
          - rate DECIMAL(18,8)
          - effective_at TIMESTAMPTZ
          - created_at TIMESTAMPTZ
        indexes:
          - idx_currency_rates_from_to
          - idx_currency_rates_effective

      - name: wallet_limits
        file: "08-wallet_limits.sql"
        columns:
          - id UUID PRIMARY KEY
          - wallet_id UUID REFERENCES financial.wallets UNIQUE
          - daily_deposit_limit DECIMAL(15,2)
          - daily_withdrawal_limit DECIMAL(15,2)
          - monthly_deposit_limit DECIMAL(15,2)
          - monthly_withdrawal_limit DECIMAL(15,2)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: financial.wallets
        indexes:
          - idx_wallet_limits_wallet

      - name: customers
        file: "09-customers.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users UNIQUE
          - stripe_customer_id VARCHAR(255) UNIQUE
          - email CITEXT
          - metadata JSONB
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_customers_user
          - idx_customers_stripe_id

      - name: payment_methods
        file: "10-payment_methods.sql"
        columns:
          - id UUID PRIMARY KEY
          - customer_id UUID REFERENCES financial.customers
          - type financial.payment_method
          - stripe_payment_method_id VARCHAR(255)
          - last_four VARCHAR(4)
          - is_default BOOLEAN
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: financial.customers
        indexes:
          - idx_payment_methods_customer
          - idx_payment_methods_stripe_id

    functions:
      - name: update_wallet_balance
        file: "01-update_wallet_balance.sql"
      - name: validate_transaction
        file: "02-validate_transaction.sql"
      - name: triggers
        file: "03-triggers.sql"

    triggers: []

  investment:
    description: "Sistema de inversiones PAMM"
    enums:
      - investment.trading_agent
      - investment.risk_profile
      - investment.account_status
      - investment.distribution_frequency
      - investment.transaction_type
      - investment.transaction_status
    tables:
      - name: products
        file: "01-products.sql"
        columns:
          - id UUID PRIMARY KEY
          - agent investment.trading_agent
          - name VARCHAR(100)
          - description TEXT
          - min_investment DECIMAL(15,2)
          - expected_return_min DECIMAL(5,2)
          - expected_return_max DECIMAL(5,2)
          - risk_profile investment.risk_profile
          - active BOOLEAN
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        indexes:
          - idx_products_agent
          - idx_products_active

      - name: risk_questionnaire
        file: "02-risk_questionnaire.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - answers JSONB
          - calculated_profile investment.risk_profile
          - score INTEGER
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_risk_questionnaire_user

      - name: accounts
        file: "03-accounts.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - product_id UUID REFERENCES investment.products
          - wallet_id UUID REFERENCES financial.wallets
          - account_number VARCHAR(20) UNIQUE
          - status investment.account_status
          - balance DECIMAL(20,8)
          - invested_capital DECIMAL(20,8)
          - accumulated_returns DECIMAL(20,8)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
          - references: investment.products
          - references: financial.wallets
        indexes:
          - idx_accounts_user
          - idx_accounts_product
          - idx_accounts_status
          - idx_accounts_account_number

      - name: distributions
        file: "04-distributions.sql"
        columns:
          - id UUID PRIMARY KEY
          - account_id UUID REFERENCES investment.accounts
          - period_start TIMESTAMPTZ
          - period_end TIMESTAMPTZ
          - gross_profit DECIMAL(20,8)
          - platform_fee DECIMAL(20,8)
          - net_profit DECIMAL(20,8)
          - roi_percentage DECIMAL(8,4)
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: investment.accounts
        indexes:
          - idx_distributions_account
          - idx_distributions_period

      - name: transactions
        file: "05-transactions.sql"
        columns:
          - id UUID PRIMARY KEY
          - account_id UUID REFERENCES investment.accounts
          - transaction_type investment.transaction_type
          - amount DECIMAL(20,8)
          - status investment.transaction_status
          - balance_after DECIMAL(20,8)
          - created_at TIMESTAMPTZ
          - completed_at TIMESTAMPTZ
        foreign_keys:
          - references: investment.accounts
        indexes:
          - idx_transactions_account
          - idx_transactions_type
          - idx_transactions_status
          - idx_transactions_created

      - name: withdrawal_requests
        file: "06-withdrawal_requests.sql"
        columns:
          - id UUID PRIMARY KEY
          - account_id UUID REFERENCES investment.accounts
          - amount DECIMAL(20,8)
          - status investment.transaction_status
          - requested_at TIMESTAMPTZ
          - processed_at TIMESTAMPTZ
        foreign_keys:
          - references: investment.accounts
        indexes:
          - idx_withdrawal_requests_account
          - idx_withdrawal_requests_status

      - name: daily_performance
        file: "07-daily_performance.sql"
        columns:
          - id UUID PRIMARY KEY
          - product_id UUID REFERENCES investment.products
          - date DATE UNIQUE
          - daily_return DECIMAL(8,4)
          - cumulative_return DECIMAL(8,4)
          - nav DECIMAL(20,8)
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: investment.products
        indexes:
          - idx_daily_performance_product
          - idx_daily_performance_date

      - name: distribution_history
        file: "08-distribution_history.sql"
        columns:
          - id UUID PRIMARY KEY
          - distribution_id UUID REFERENCES investment.distributions
          - action VARCHAR(50)
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: investment.distributions
        indexes:
          - idx_distribution_history_distribution

      - name: distribution_runs
        file: "09-distribution_runs.sql"
        columns:
          - id UUID PRIMARY KEY
          - period_start TIMESTAMPTZ
          - period_end TIMESTAMPTZ
          - total_accounts INTEGER
          - total_distributed DECIMAL(20,8)
          - status VARCHAR(20)
          - started_at TIMESTAMPTZ
          - completed_at TIMESTAMPTZ
        indexes:
          - idx_distribution_runs_period
          - idx_distribution_runs_status

    functions: []
    triggers: []

  llm:
    description: "Sistema de conversación con LLM"
    enums:
      - llm.conversation_status
      - llm.message_role
      - llm.model_provider
    tables:
      - name: conversations
        file: "01-conversations.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - title VARCHAR(255)
          - status llm.conversation_status
          - metadata JSONB
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_conversations_user
          - idx_conversations_status

      - name: messages
        file: "02-messages.sql"
        columns:
          - id UUID PRIMARY KEY
          - conversation_id UUID REFERENCES llm.conversations
          - role llm.message_role
          - content TEXT
          - model_provider llm.model_provider
          - tokens_used INTEGER
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: llm.conversations
        indexes:
          - idx_messages_conversation
          - idx_messages_created

      - name: user_preferences
        file: "03-user_preferences.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users UNIQUE
          - preferred_model VARCHAR(50)
          - temperature DECIMAL(3,2)
          - max_tokens INTEGER
          - system_prompt TEXT
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_user_preferences_user

      - name: user_memory
        file: "04-user_memory.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - memory_key VARCHAR(100)
          - memory_value JSONB
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_user_memory_user
          - idx_user_memory_key

      - name: embeddings
        file: "05-embeddings.sql"
        columns:
          - id UUID PRIMARY KEY
          - conversation_id UUID REFERENCES llm.conversations
          - message_id UUID REFERENCES llm.messages
          - embedding vector(1536)
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: llm.conversations
          - references: llm.messages
        indexes:
          - idx_embeddings_conversation
          - idx_embeddings_message

    functions: []
    triggers: []

  market_data:
    description: "Datos de mercado OHLCV"
    enums:
      - market_data.data_source
      - market_data.sync_status
    tables:
      - name: tickers
        file: "01-tickers.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20) UNIQUE
          - exchange VARCHAR(50)
          - base_currency VARCHAR(10)
          - quote_currency VARCHAR(10)
          - active BOOLEAN
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        indexes:
          - idx_tickers_symbol
          - idx_tickers_exchange
          - idx_tickers_active

      - name: ohlcv_5m
        file: "02-ohlcv_5m.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - timestamp TIMESTAMPTZ
          - open DECIMAL(18,8)
          - high DECIMAL(18,8)
          - low DECIMAL(18,8)
          - close DECIMAL(18,8)
          - volume DECIMAL(20,8)
        indexes:
          - idx_ohlcv_5m_symbol_timestamp

      - name: ohlcv_15m
        file: "03-ohlcv_15m.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - timestamp TIMESTAMPTZ
          - open DECIMAL(18,8)
          - high DECIMAL(18,8)
          - low DECIMAL(18,8)
          - close DECIMAL(18,8)
          - volume DECIMAL(20,8)
        indexes:
          - idx_ohlcv_15m_symbol_timestamp

      - name: staging
        file: "04-staging.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - timestamp TIMESTAMPTZ
          - data JSONB
          - source market_data.data_source
          - status market_data.sync_status
          - created_at TIMESTAMPTZ
        indexes:
          - idx_staging_symbol
          - idx_staging_status

    functions: []
    triggers: []

  ml:
    description: "Sistema de Machine Learning y predicciones"
    enums:
      - ml.model_type
      - ml.framework
      - ml.model_status
      - ml.prediction_type
      - ml.prediction_result
      - ml.outcome_status
    tables:
      - name: models
        file: "01-models.sql"
        columns:
          - id UUID PRIMARY KEY
          - name VARCHAR(100) UNIQUE
          - model_type ml.model_type
          - framework ml.framework
          - status ml.model_status
          - description TEXT
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        indexes:
          - idx_models_name
          - idx_models_status

      - name: model_versions
        file: "02-model_versions.sql"
        columns:
          - id UUID PRIMARY KEY
          - model_id UUID REFERENCES ml.models
          - version VARCHAR(20)
          - artifact_path TEXT
          - metrics JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: ml.models
        indexes:
          - idx_model_versions_model
          - idx_model_versions_version

      - name: predictions
        file: "03-predictions.sql"
        columns:
          - id UUID PRIMARY KEY
          - model_version_id UUID REFERENCES ml.model_versions
          - symbol VARCHAR(20)
          - prediction_type ml.prediction_type
          - result ml.prediction_result
          - confidence DECIMAL(5,4)
          - target_price DECIMAL(18,8)
          - timeframe VARCHAR(10)
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: ml.model_versions
        indexes:
          - idx_predictions_model_version
          - idx_predictions_symbol
          - idx_predictions_created

      - name: prediction_outcomes
        file: "04-prediction_outcomes.sql"
        columns:
          - id UUID PRIMARY KEY
          - prediction_id UUID REFERENCES ml.predictions
          - outcome_status ml.outcome_status
          - actual_price DECIMAL(18,8)
          - evaluated_at TIMESTAMPTZ
        foreign_keys:
          - references: ml.predictions
        indexes:
          - idx_prediction_outcomes_prediction
          - idx_prediction_outcomes_status

      - name: feature_store
        file: "05-feature_store.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - timestamp TIMESTAMPTZ
          - features JSONB
          - created_at TIMESTAMPTZ
        indexes:
          - idx_feature_store_symbol_timestamp

      - name: llm_predictions
        file: "06-llm_predictions.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - model_provider VARCHAR(50)
          - prediction ml.prediction_result
          - reasoning TEXT
          - confidence DECIMAL(5,4)
          - created_at TIMESTAMPTZ
        indexes:
          - idx_llm_predictions_symbol
          - idx_llm_predictions_created

      - name: llm_prediction_outcomes
        file: "07-llm_prediction_outcomes.sql"
        columns:
          - id UUID PRIMARY KEY
          - llm_prediction_id UUID REFERENCES ml.llm_predictions
          - outcome_status ml.outcome_status
          - actual_price DECIMAL(18,8)
          - evaluated_at TIMESTAMPTZ
        foreign_keys:
          - references: ml.llm_predictions
        indexes:
          - idx_llm_prediction_outcomes_prediction

      - name: llm_decisions
        file: "08-llm_decisions.sql"
        columns:
          - id UUID PRIMARY KEY
          - bot_id UUID REFERENCES trading.bots
          - order_id UUID REFERENCES trading.orders
          - reasoning TEXT
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.bots
          - references: trading.orders
        indexes:
          - idx_llm_decisions_bot
          - idx_llm_decisions_order

      - name: risk_events
        file: "09-risk_events.sql"
        columns:
          - id UUID PRIMARY KEY
          - bot_id UUID REFERENCES trading.bots
          - event_type VARCHAR(50)
          - severity VARCHAR(20)
          - description TEXT
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.bots
        indexes:
          - idx_risk_events_bot
          - idx_risk_events_severity
          - idx_risk_events_created

      - name: backtest_runs
        file: "10-backtest_runs.sql"
        columns:
          - id UUID PRIMARY KEY
          - model_version_id UUID REFERENCES ml.model_versions
          - start_date DATE
          - end_date DATE
          - initial_capital DECIMAL(20,8)
          - final_capital DECIMAL(20,8)
          - total_return DECIMAL(8,4)
          - sharpe_ratio DECIMAL(6,4)
          - max_drawdown DECIMAL(6,4)
          - total_trades INTEGER
          - win_rate DECIMAL(5,4)
          - metadata JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: ml.model_versions
        indexes:
          - idx_backtest_runs_model_version
          - idx_backtest_runs_created

      - name: llm_signals
        file: "11-llm_signals.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - signal_type VARCHAR(20)
          - reasoning TEXT
          - confidence DECIMAL(5,4)
          - metadata JSONB
          - created_at TIMESTAMPTZ
        indexes:
          - idx_llm_signals_symbol
          - idx_llm_signals_created

    functions: []
    triggers: []

  portfolio:
    description: "Gestión de portafolios"
    enums:
      - portfolio.risk_profile
      - portfolio.goal_status
      - portfolio.rebalance_action
      - portfolio.allocation_status
    tables:
      - name: portfolios
        file: "01-portfolios.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - name VARCHAR(100)
          - description TEXT
          - risk_profile portfolio.risk_profile
          - total_value DECIMAL(20,8)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_portfolios_user

      - name: portfolio_allocations
        file: "02-portfolio_allocations.sql"
        columns:
          - id UUID PRIMARY KEY
          - portfolio_id UUID REFERENCES portfolio.portfolios
          - symbol VARCHAR(20)
          - target_percentage DECIMAL(5,2)
          - current_percentage DECIMAL(5,2)
          - current_value DECIMAL(20,8)
          - status portfolio.allocation_status
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: portfolio.portfolios
        indexes:
          - idx_portfolio_allocations_portfolio
          - idx_portfolio_allocations_symbol

      - name: portfolio_goals
        file: "03-portfolio_goals.sql"
        columns:
          - id UUID PRIMARY KEY
          - portfolio_id UUID REFERENCES portfolio.portfolios
          - goal_name VARCHAR(100)
          - target_amount DECIMAL(20,8)
          - target_date DATE
          - status portfolio.goal_status
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: portfolio.portfolios
        indexes:
          - idx_portfolio_goals_portfolio
          - idx_portfolio_goals_status

      - name: rebalance_history
        file: "04-rebalance_history.sql"
        columns:
          - id UUID PRIMARY KEY
          - portfolio_id UUID REFERENCES portfolio.portfolios
          - symbol VARCHAR(20)
          - action portfolio.rebalance_action
          - quantity DECIMAL(20,8)
          - price DECIMAL(18,8)
          - executed_at TIMESTAMPTZ
        foreign_keys:
          - references: portfolio.portfolios
        indexes:
          - idx_rebalance_history_portfolio
          - idx_rebalance_history_executed

      - name: portfolio_snapshots
        file: "05-portfolio_snapshots.sql"
        columns:
          - id UUID PRIMARY KEY
          - portfolio_id UUID REFERENCES portfolio.portfolios
          - snapshot_date DATE
          - total_value DECIMAL(20,8)
          - daily_return DECIMAL(8,4)
          - allocations JSONB
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: portfolio.portfolios
        indexes:
          - idx_portfolio_snapshots_portfolio
          - idx_portfolio_snapshots_date

    functions: []
    triggers: []

  trading:
    description: "Sistema de trading y bots"
    enums:
      - trading.order_type
      - trading.order_status
      - trading.order_side
      - trading.position_status
      - trading.signal_type
      - trading.confidence_level
      - trading.timeframe
      - trading.bot_type
      - trading.bot_status
    tables:
      - name: symbols
        file: "01-symbols.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20) UNIQUE
          - base_currency VARCHAR(10)
          - quote_currency VARCHAR(10)
          - exchange VARCHAR(50)
          - min_order_size DECIMAL(18,8)
          - max_order_size DECIMAL(18,8)
          - price_precision INTEGER
          - quantity_precision INTEGER
          - active BOOLEAN
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        indexes:
          - idx_symbols_symbol
          - idx_symbols_exchange
          - idx_symbols_active

      - name: watchlists
        file: "02-watchlists.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - name VARCHAR(100)
          - description TEXT
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_watchlists_user

      - name: watchlist_items
        file: "03-watchlist_items.sql"
        columns:
          - id UUID PRIMARY KEY
          - watchlist_id UUID REFERENCES trading.watchlists
          - symbol VARCHAR(20)
          - sort_order INTEGER
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.watchlists
        indexes:
          - idx_watchlist_items_watchlist
          - idx_watchlist_items_symbol

      - name: bots
        file: "04-bots.sql"
        columns:
          - id UUID PRIMARY KEY
          - user_id UUID REFERENCES auth.users
          - name VARCHAR(100)
          - bot_type trading.bot_type
          - status trading.bot_status
          - symbols VARCHAR(20)[]
          - timeframe trading.timeframe
          - initial_capital DECIMAL(20,8)
          - current_capital DECIMAL(20,8)
          - max_position_size_pct DECIMAL(5,2)
          - max_daily_loss_pct DECIMAL(5,2)
          - strategy_type VARCHAR(50)
          - strategy_config JSONB
          - total_trades INTEGER
          - winning_trades INTEGER
          - total_profit_loss DECIMAL(20,8)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: auth.users
        indexes:
          - idx_bots_user
          - idx_bots_status
          - idx_bots_type

      - name: orders
        file: "05-orders.sql"
        columns:
          - id UUID PRIMARY KEY
          - bot_id UUID REFERENCES trading.bots
          - symbol VARCHAR(20)
          - order_type trading.order_type
          - order_side trading.order_side
          - status trading.order_status
          - price DECIMAL(18,8)
          - quantity DECIMAL(18,8)
          - filled_quantity DECIMAL(18,8)
          - average_price DECIMAL(18,8)
          - exchange_order_id VARCHAR(100)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.bots
        indexes:
          - idx_orders_bot
          - idx_orders_symbol
          - idx_orders_status
          - idx_orders_created

      - name: positions
        file: "06-positions.sql"
        columns:
          - id UUID PRIMARY KEY
          - bot_id UUID REFERENCES trading.bots
          - symbol VARCHAR(20)
          - status trading.position_status
          - entry_price DECIMAL(18,8)
          - current_price DECIMAL(18,8)
          - quantity DECIMAL(18,8)
          - unrealized_pnl DECIMAL(20,8)
          - realized_pnl DECIMAL(20,8)
          - opened_at TIMESTAMPTZ
          - closed_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.bots
        indexes:
          - idx_positions_bot
          - idx_positions_symbol
          - idx_positions_status

      - name: trades
        file: "07-trades.sql"
        columns:
          - id UUID PRIMARY KEY
          - order_id UUID REFERENCES trading.orders
          - position_id UUID REFERENCES trading.positions
          - price DECIMAL(18,8)
          - quantity DECIMAL(18,8)
          - fee DECIMAL(18,8)
          - executed_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.orders
          - references: trading.positions
        indexes:
          - idx_trades_order
          - idx_trades_position
          - idx_trades_executed

      - name: signals
        file: "08-signals.sql"
        columns:
          - id UUID PRIMARY KEY
          - symbol VARCHAR(20)
          - signal_type trading.signal_type
          - confidence trading.confidence_level
          - price DECIMAL(18,8)
          - metadata JSONB
          - created_at TIMESTAMPTZ
        indexes:
          - idx_signals_symbol
          - idx_signals_type
          - idx_signals_created

      - name: trading_metrics
        file: "09-trading_metrics.sql"
        columns:
          - id UUID PRIMARY KEY
          - bot_id UUID REFERENCES trading.bots
          - date DATE
          - total_trades INTEGER
          - winning_trades INTEGER
          - losing_trades INTEGER
          - gross_profit DECIMAL(20,8)
          - gross_loss DECIMAL(20,8)
          - net_profit DECIMAL(20,8)
          - win_rate DECIMAL(5,4)
          - profit_factor DECIMAL(6,4)
          - created_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.bots
        indexes:
          - idx_trading_metrics_bot
          - idx_trading_metrics_date

      - name: paper_balances
        file: "10-paper_balances.sql"
        columns:
          - id UUID PRIMARY KEY
          - bot_id UUID REFERENCES trading.bots UNIQUE
          - balance DECIMAL(20,8)
          - equity DECIMAL(20,8)
          - created_at TIMESTAMPTZ
          - updated_at TIMESTAMPTZ
        foreign_keys:
          - references: trading.bots
        indexes:
          - idx_paper_balances_bot

    functions: []
    triggers: []

# ==============================================================================
# Summary Statistics
# ==============================================================================
statistics:
  by_schema:
    audit: 7
    auth: 13
    education: 15
    financial: 10
    investment: 9
    llm: 5
    market_data: 4
    ml: 11
    portfolio: 5
    trading: 10

  foreign_key_relationships:
    auth.users: "Referenced by 40+ tables across all schemas"
    trading.bots: "Referenced by orders, positions, ml.llm_decisions, ml.risk_events"
    financial.wallets: "Referenced by transactions, audit_log, investment.accounts"
    investment.products: "Referenced by accounts, daily_performance"
    education.courses: "Referenced by modules, enrollments, reviews, certificates"

  critical_tables:
    - auth.users (foundation for all user operations)
    - financial.wallets (financial foundation)
    - trading.bots (trading foundation)
    - investment.accounts (investment foundation)
    - ml.models (ML foundation)
