-- ============================================
-- BILLING: Payment Methods Table
-- Version: 1.0.0
-- ============================================

CREATE TABLE IF NOT EXISTS billing.payment_methods (
  id                        UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id                 UUID NOT NULL REFERENCES tenants.tenants(id) ON DELETE CASCADE,

  -- Type and provider
  type                      billing.payment_method_type NOT NULL DEFAULT 'card',
  payment_provider          VARCHAR(50),            -- stripe, conekta, etc.
  external_payment_method_id VARCHAR(255),          -- ID from provider

  -- Card details (masked)
  card_last_four            VARCHAR(4),
  card_brand                VARCHAR(20),            -- visa, mastercard, amex
  card_exp_month            SMALLINT,
  card_exp_year             SMALLINT,

  -- Status
  is_default                BOOLEAN NOT NULL DEFAULT FALSE,
  is_active                 BOOLEAN NOT NULL DEFAULT TRUE,

  -- Metadata
  metadata                  JSONB,

  -- Timestamps
  created_at                TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
  updated_at                TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_payment_methods_tenant ON billing.payment_methods(tenant_id);
CREATE INDEX idx_payment_methods_default ON billing.payment_methods(tenant_id, is_default) WHERE is_default = TRUE;
CREATE INDEX idx_payment_methods_active ON billing.payment_methods(tenant_id, is_active) WHERE is_active = TRUE;
CREATE INDEX idx_payment_methods_provider ON billing.payment_methods(external_payment_method_id) WHERE external_payment_method_id IS NOT NULL;

-- Row Level Security
ALTER TABLE billing.payment_methods ENABLE ROW LEVEL SECURITY;

CREATE POLICY payment_methods_tenant_isolation ON billing.payment_methods
  USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid);

-- Updated at trigger
CREATE TRIGGER trg_payment_methods_updated_at
  BEFORE UPDATE ON billing.payment_methods
  FOR EACH ROW EXECUTE FUNCTION billing.update_updated_at();

-- Comments
COMMENT ON TABLE billing.payment_methods IS 'Stored payment methods for tenants';
COMMENT ON COLUMN billing.payment_methods.type IS 'Type: card, bank_transfer, oxxo';
COMMENT ON COLUMN billing.payment_methods.external_payment_method_id IS 'Payment method ID from payment provider';
COMMENT ON COLUMN billing.payment_methods.is_default IS 'Whether this is the default payment method';
COMMENT ON COLUMN billing.payment_methods.is_active IS 'Whether this payment method can be used';
