-- Terms Agreements Table
-- Stores legal audit trail for Terms & Conditions acceptance at signup

CREATE TABLE IF NOT EXISTS terms_agreements (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id VARCHAR(255) NOT NULL,
  agreed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  ip_address VARCHAR(45) NOT NULL,
  user_agent TEXT NOT NULL,
  terms_version VARCHAR(50) NOT NULL,
  terms_url VARCHAR(255) NOT NULL,
  terms_content_hash VARCHAR(64) NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Index for user lookup
CREATE INDEX IF NOT EXISTS idx_terms_agreements_user_id ON terms_agreements(user_id);

-- Trigger for updated_at
CREATE OR REPLACE FUNCTION update_terms_agreements_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = CURRENT_TIMESTAMP;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS terms_agreements_updated_at ON terms_agreements;
CREATE TRIGGER terms_agreements_updated_at
  BEFORE UPDATE ON terms_agreements
  FOR EACH ROW
  EXECUTE FUNCTION update_terms_agreements_updated_at();
