-- Script para criar a tabela de proxies
-- Execute este script no seu banco de dados PostgreSQL

CREATE TABLE IF NOT EXISTS proxies (
    id SERIAL PRIMARY KEY,
    ip_address VARCHAR(255) NOT NULL,
    port INTEGER NOT NULL,
    protocol VARCHAR(10) NOT NULL DEFAULT 'http',
    username VARCHAR(255),
    password VARCHAR(255),
    country_code VARCHAR(10),
    country_name VARCHAR(100),
    city VARCHAR(100),
    is_active BOOLEAN DEFAULT TRUE,
    is_anonymous BOOLEAN DEFAULT FALSE,
    response_time_ms INTEGER,
    last_checked_at TIMESTAMP,
    last_successful_at TIMESTAMP,
    failure_count INTEGER DEFAULT 0,
    success_count INTEGER DEFAULT 0,
    usage VARCHAR(50),
    source VARCHAR(100),
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT check_protocol CHECK (protocol IN ('http', 'https', 'socks5', 'socks4'))
);

-- Índices para melhorar performance
CREATE INDEX IF NOT EXISTS idx_proxies_is_active ON proxies(is_active);
CREATE INDEX IF NOT EXISTS idx_proxies_last_successful_at ON proxies(last_successful_at DESC NULLS LAST);
CREATE INDEX IF NOT EXISTS idx_proxies_response_time ON proxies(response_time_ms ASC NULLS LAST);
CREATE INDEX IF NOT EXISTS idx_proxies_created_at ON proxies(created_at DESC);

-- Trigger para atualizar updated_at automaticamente
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_proxies_updated_at BEFORE UPDATE ON proxies
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Exemplo de inserção de proxies (remova ou ajuste conforme necessário)
-- INSERT INTO proxies (ip_address, port, protocol, is_active, is_anonymous) VALUES
--     ('123.456.789.10', 8080, 'http', TRUE, FALSE),
--     ('98.765.432.10', 3128, 'https', TRUE, TRUE),
--     ('45.67.89.100', 1080, 'socks5', TRUE, TRUE);

-- Exemplo com autenticação
-- INSERT INTO proxies (ip_address, port, protocol, username, password, is_active) VALUES
--     ('proxy.example.com', 8080, 'http', 'user123', 'pass456', TRUE);
