# frozen_string_literal: true

class Create<%= class_name %>ItemsAndAccounts < ActiveRecord::Migration<%= migration_version %>
  def change
    # Create provider items table (stores per-family connection credentials)
    create_table :<%= table_name %>, id: :uuid do |t|
      t.references :family, null: false, foreign_key: true, type: :uuid
      t.string :name

      # Institution metadata
      t.string :institution_id
      t.string :institution_name
      t.string :institution_domain
      t.string :institution_url
      t.string :institution_color

      # Status and lifecycle
      t.string :status, default: "good"
      t.boolean :scheduled_for_deletion, default: false
      t.boolean :pending_account_setup, default: false

      # Sync settings
      t.datetime :sync_start_date

      # Raw data storage
      t.jsonb :raw_payload
      t.jsonb :raw_institution_payload

      # Provider-specific credential fields
<% parsed_fields.each do |field| -%>
      t.<%= field[:type] %> :<%= field[:name] %>
<% end -%>

      t.timestamps
    end

    add_index :<%= table_name %>, :status

    # Create provider accounts table (stores individual account data from provider)
    create_table :<%= file_name %>_accounts, id: :uuid do |t|
      t.references :<%= file_name %>_item, null: false, foreign_key: true, type: :uuid

      # Account identification
      t.string :name
      t.string :<%= file_name %>_account_id
      t.string :account_number

      # Account details
      t.string :currency
      t.decimal :current_balance, precision: 19, scale: 4
      t.string :account_status
      t.string :account_type
      t.string :provider

      # Metadata and raw data
      t.jsonb :institution_metadata
      t.jsonb :raw_payload
<% if banking_provider? -%>
      t.jsonb :raw_transactions_payload
<% end -%>
<% if investment_provider? -%>

      # Investment-specific columns
      t.string :<%= file_name %>_authorization_id
      t.decimal :cash_balance, precision: 19, scale: 4, default: 0.0
      t.jsonb :raw_holdings_payload, default: []
      t.jsonb :raw_activities_payload, default: []
      t.datetime :last_holdings_sync
      t.datetime :last_activities_sync
      t.boolean :activities_fetch_pending, default: false
<% end -%>

      # Sync settings
      t.date :sync_start_date

      t.timestamps
    end

    add_index :<%= file_name %>_accounts, :<%= file_name %>_account_id, unique: true
<% if investment_provider? -%>
    add_index :<%= file_name %>_accounts, :<%= file_name %>_authorization_id
<% end -%>
  end
end
