package database

import (
	"time"
)

// Parameter representa un parámetro en la base de datos
type Parameter struct {
	ID          int       `db:"id"`
	Key         string    `db:"key"`
	Value       string    `db:"value"`
	Description string    `db:"description"`
	Active      bool      `db:"active"`
	CreatedAt   time.Time `db:"created_at"`
	UpdatedAt   time.Time `db:"updated_at"`
}

// Estructura para las solicitudes SOAP
type SoapRequest struct {
	ID             int       `db:"id"`
	RequestID      string    `db:"request_id"`
	APIID          string    `db:"api_id"`
	OperationName  string    `db:"operation_name"`
	RequestBody    string    `db:"request_body"`
	ResponseBody   string    `db:"response_body"`
	StatusCode     int       `db:"status_code"`
	Error          string    `db:"error"`
	RequestTime    time.Time `db:"request_time"`
	ResponseTime   time.Time `db:"response_time"`
	ProcessingTime int64     `db:"processing_time"`
	CreatedAt      time.Time `db:"created_at"`
}

// Inicialización de la base de datos: script SQL
const DatabaseInitSQL = `
-- Tabla de parámetros
CREATE TABLE IF NOT EXISTS parameters (
    id SERIAL PRIMARY KEY,
    key VARCHAR(100) NOT NULL UNIQUE,
    value TEXT NOT NULL,
    description TEXT,
    active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Tabla para registro de solicitudes SOAP
CREATE TABLE IF NOT EXISTS soap_requests (
    id SERIAL PRIMARY KEY,
    request_id VARCHAR(36) NOT NULL,
    api_id VARCHAR(50) NOT NULL,
    operation_name VARCHAR(100) NOT NULL,
    request_body TEXT NOT NULL,
    response_body TEXT,
    status_code INT,
    error TEXT,
    request_time TIMESTAMP WITH TIME ZONE NOT NULL,
    response_time TIMESTAMP WITH TIME ZONE,
    processing_time BIGINT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Índices
CREATE INDEX IF NOT EXISTS idx_soap_requests_request_id ON soap_requests(request_id);
CREATE INDEX IF NOT EXISTS idx_soap_requests_api_id ON soap_requests(api_id);
CREATE INDEX IF NOT EXISTS idx_soap_requests_operation_name ON soap_requests(operation_name);
CREATE INDEX IF NOT EXISTS idx_soap_requests_request_time ON soap_requests(request_time);

-- Insertar parámetros iniciales
INSERT INTO parameters (key, value, description) 
VALUES 
    ('soap.api1.endpoint', 'https://api1.example.com/soap', 'Endpoint for API 1'),
    ('soap.api2.endpoint', 'https://api2.example.com/soap', 'Endpoint for API 2')
ON CONFLICT (key) DO NOTHING;
`
