-- Database Schema for Domain Verification Feature
-- Run this migration to create the necessary tables

-- Verification Requests Table
CREATE TABLE IF NOT EXISTS domain_verifications (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL,
  domain VARCHAR(255) NOT NULL,
  verification_token VARCHAR(64) NOT NULL,
  verification_type VARCHAR(20) CHECK (verification_type IN ('dns', 'blockchain')) DEFAULT 'dns',
  verified BOOLEAN DEFAULT false,
  created_at TIMESTAMP DEFAULT NOW(),
  verified_at TIMESTAMP,
  expires_at TIMESTAMP DEFAULT NOW() + INTERVAL '7 days',
  CONSTRAINT unique_user_domain UNIQUE(user_id, domain)
);

-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_domain_verifications_user_id ON domain_verifications(user_id);
CREATE INDEX IF NOT EXISTS idx_domain_verifications_domain ON domain_verifications(domain);
CREATE INDEX IF NOT EXISTS idx_domain_verifications_verified ON domain_verifications(verified);

-- User Profiles Table to store extended user information
CREATE TABLE IF NOT EXISTS user_profiles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL UNIQUE,
  verified_domain VARCHAR(255),
  domain_verified_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Create index for verified domains
CREATE INDEX IF NOT EXISTS idx_user_profiles_verified_domain ON user_profiles(verified_domain) WHERE verified_domain IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_user_profiles_user_id ON user_profiles(user_id);

-- Comments for documentation
COMMENT ON TABLE domain_verifications IS 'Stores domain verification requests and their status';
COMMENT ON COLUMN domain_verifications.verification_token IS 'Unique token to be added to DNS TXT record or wallet address for blockchain verification';
COMMENT ON COLUMN domain_verifications.verification_type IS 'Type of verification: dns for traditional domains, blockchain for .aethex domains';
COMMENT ON COLUMN domain_verifications.expires_at IS 'Verification request expires after 7 days';
