CREATE EXTENSION IF NOT EXISTS timescaledb;

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TYPE aggregation_state AS ENUM ('RESTARTED', 'STARTED', 'AGGREGATED', 'DELETED', 'ADDED', 'COMPLETED');
CREATE TYPE aggregation_type AS ENUM ('DAILY', 'MONTHLY', 'YEARLY');

CREATE TABLE "aggregation_status"(
	id UUID NOT NULL PRIMARY KEY DEFAULT uuid_generate_v4 (),
	record_type TEXT NOT NULL,
	aggregation_type aggregation_type NOT NULL,
	aggregation_start_date TIMESTAMP WITH TIME ZONE NOT NULL,
	aggregation_end_date TIMESTAMP WITH TIME ZONE NOT NULL,
	original_records_number NUMERIC NOT NULL,
	aggregated_records_number NUMERIC NOT NULL,
	recovered_records_number NUMERIC NOT NULL,
	malformed_records_number NUMERIC NOT NULL DEFAULT 0,
	percentage NUMERIC NOT NULL,
	restart_from NUMERIC NOT NULL DEFAULT 0,
	context TEXT,
	current_aggregation_state aggregation_state NOT NULL,
	last_update_time TIMESTAMP WITH TIME ZONE NOT NULL,
	previous UUID REFERENCES aggregation_status (id) DEFAULT NULL ON DELETE SET NULL
);

CREATE TABLE "aggregation_status_event"(
	aggregation_state aggregation_state NOT NULL,
	start_time TIMESTAMP WITH TIME ZONE NOT NULL,
	end_time TIMESTAMP WITH TIME ZONE NOT NULL,
	aggregation_status UUID REFERENCES aggregation_status (id) ON DELETE CASCADE,
	UNIQUE (aggregation_state, start_time, end_time, aggregation_status)
);