class AddClubBillingAndDocuments < ActiveRecord::Migration[7.2]
  def change
    change_table :clubs, bulk: true do |t|
      t.string :billing_entity_type, default: "company", null: false
      t.string :billing_legal_name
      t.string :billing_vat_number
      t.string :billing_fiscal_code
      t.string :billing_email
      t.string :billing_phone
      t.string :billing_address_line
      t.string :billing_city
      t.string :billing_province, limit: 2
      t.string :billing_postal_code
      t.string :billing_country, default: "IT", null: false
      t.string :billing_recipient_code, limit: 7
      t.string :billing_pec
    end

    create_table :billing_payments, id: :uuid do |t|
      t.references :club, null: false, foreign_key: true, type: :uuid
      t.string :stripe_invoice_id
      t.string :stripe_payment_intent_id
      t.string :stripe_charge_id
      t.integer :amount_cents, null: false
      t.string :currency, default: "eur", null: false
      t.string :status, default: "paid", null: false
      t.string :plan_slug
      t.string :description
      t.datetime :paid_at
      t.string :invoice_pdf_url
      t.string :receipt_url
      t.timestamps
    end

    add_index :billing_payments, :stripe_invoice_id, unique: true, where: "stripe_invoice_id IS NOT NULL"
    add_index :billing_payments, [:club_id, :paid_at]

    create_table :billing_invoices, id: :uuid do |t|
      t.references :club, null: false, foreign_key: true, type: :uuid
      t.references :billing_payment, foreign_key: true, type: :uuid
      t.string :number, null: false
      t.date :issued_on, null: false
      t.integer :amount_cents, null: false
      t.string :currency, default: "eur", null: false
      t.string :status, default: "issued", null: false
      t.string :source, default: "aruba", null: false
      t.string :aruba_document_id
      t.text :notes
      t.timestamps
    end

    add_index :billing_invoices, [:club_id, :number], unique: true
    add_index :billing_invoices, [:club_id, :issued_on]
  end
end
