begin;
DROP TABLE correos.destinatarios;
DROP TABLE correos.cartas;
--DROP TABLE correos.origenes;
DROP TABLE correos.direcciones;
DROP TABLE correos.mxrecords;
DROP TABLE correos.arecords;
DROP TABLE correos.ipv4addrs;
DROP TABLE correos.fqdns;

DROP SCHEMA correos;


CREATE SCHEMA correos;

CREATE TABLE correos.fqdns (
	id SERIAL NOT NULL, 
	fqdn VARCHAR, 
	PRIMARY KEY (id), 
	UNIQUE (fqdn)
);

CREATE TABLE correos.ipv4addrs (
	id SERIAL NOT NULL, 
	ipaddr INET NOT NULL, 
	PRIMARY KEY (id), 
	UNIQUE (ipaddr)
);

CREATE TABLE correos.direcciones (
	id SERIAL NOT NULL, 
	direccion VARCHAR NOT NULL, 
	dominioid INTEGER NOT NULL, 
	nombre VARCHAR, 
	PRIMARY KEY (id), 
	UNIQUE (direccion), 
	FOREIGN KEY(dominioid) REFERENCES correos.fqdns (id)
);

CREATE TABLE correos.mxrecords (
	id SERIAL NOT NULL, 
	fqdnid INTEGER NOT NULL, 
	fqdnmxid INTEGER NOT NULL, 
	prioridad INTEGER DEFAULT 10000, 
	validohasta INTEGER DEFAULT 0, 
	PRIMARY KEY (id), 
	FOREIGN KEY(fqdnid) REFERENCES correos.fqdns (id)
);

CREATE TABLE correos.arecords (
	id SERIAL NOT NULL, 
	fqdnid INTEGER NOT NULL, 
	ipv4id INTEGER NOT NULL, 
	recibidos INTEGER DEFAULT 0, 
	enviados INTEGER DEFAULT 0, 
	errores INTEGER DEFAULT 0, 
	sesiones INTEGER DEFAULT 0, 
	validohasta INTEGER DEFAULT 0, 
	PRIMARY KEY (id), 
	FOREIGN KEY(fqdnid) REFERENCES correos.fqdns (id), 
	FOREIGN KEY(ipv4id) REFERENCES correos.ipv4addrs (id)
);

CREATE TABLE correos.cartas (
	id SERIAL NOT NULL, 
	remitenteid INTEGER NOT NULL, 
	contenido TEXT, 
	recibido TIMESTAMP WITH TIME ZONE, 
	PRIMARY KEY (id), 
	FOREIGN KEY(remitenteid) REFERENCES correos.direcciones (id)
);

CREATE TABLE correos.destinatarios (
	id SERIAL NOT NULL, 
	direccionid INTEGER NOT NULL, 
	cartaid INTEGER NOT NULL, 
	enviado INTEGER DEFAULT 0, 
	intentos INTEGER DEFAULT 0, 
	timestamp TIMESTAMP WITH TIME ZONE, 
	PRIMARY KEY (id), 
	FOREIGN KEY(direccionid) REFERENCES correos.direcciones (id), 
	FOREIGN KEY(cartaid) REFERENCES correos.cartas (id)
);
commit;