USE whp;

-- Add is_wildcard column to sites table
ALTER TABLE sites ADD COLUMN IF NOT EXISTS is_wildcard TINYINT(1) DEFAULT 0 COMMENT 'Whether this site handles wildcard subdomains' AFTER auto_recreate_on_update;
CREATE INDEX idx_is_wildcard ON sites (is_wildcard);

-- Add is_wildcard column to site_domains table
ALTER TABLE site_domains ADD COLUMN IF NOT EXISTS is_wildcard TINYINT(1) DEFAULT 0 COMMENT 'Whether this domain entry is a wildcard' AFTER is_primary;

-- Add is_wildcard column to haproxy_domains table
ALTER TABLE haproxy_domains ADD COLUMN IF NOT EXISTS is_wildcard TINYINT(1) DEFAULT 0 COMMENT 'Whether this is a wildcard domain for HAProxy config generation' AFTER ssl_last_renewal;
CREATE INDEX idx_is_wildcard ON haproxy_domains (is_wildcard);

-- Create dns_challenges table for DNS-01 ACME challenge tracking
CREATE TABLE IF NOT EXISTS dns_challenges (
    id INT AUTO_INCREMENT PRIMARY KEY,
    site_id INT NOT NULL,
    domain_name VARCHAR(255) NOT NULL COMMENT 'Base domain (e.g., domain.tld)',
    challenge_fqdn VARCHAR(255) NOT NULL COMMENT 'Full TXT record name (_acme-challenge.domain.tld)',
    challenge_token TEXT NOT NULL COMMENT 'TXT record value from ACME',
    status ENUM('pending', 'created', 'verified', 'completed', 'failed') NOT NULL DEFAULT 'pending',
    error_message TEXT DEFAULT NULL,
    requested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    verified_at TIMESTAMP NULL DEFAULT NULL,
    completed_at TIMESTAMP NULL DEFAULT NULL,
    FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE,
    INDEX idx_site_id (site_id),
    INDEX idx_domain_name (domain_name),
    INDEX idx_status (status),
    INDEX idx_requested_at (requested_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
