-- +goose Up
-- +goose StatementBegin
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_tables WHERE table_name = 'TB_FLASH_META_VENDA';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE '
            CREATE TABLE TB_FLASH_META_VENDA (
                ID_META          NUMBER      NOT NULL,
                ID_NODO          NUMBER      NOT NULL,
                DATA_REFERENCIA  DATE        NOT NULL,
                ANO_REFERENCIA   NUMBER(4,0) NOT NULL,
                MES_REFERENCIA   NUMBER(2,0) NOT NULL,
                DIA_REFERENCIA   NUMBER(2,0) NOT NULL,
                PERCENTUAL_META  NUMBER(10,4),
                VALOR_META       NUMBER(18,6),
                OBSERVACAO       VARCHAR2(500),
                DATA_CADASTRO    DATE DEFAULT SYSDATE NOT NULL,
                DATA_ATUALIZACAO DATE,
                CONSTRAINT CK_TB_FLASH_META_VENDA_MES CHECK (MES_REFERENCIA BETWEEN 1 AND 12),
                CONSTRAINT CK_TB_FLASH_META_VENDA_DIA CHECK (DIA_REFERENCIA BETWEEN 1 AND 31),
                CONSTRAINT PK_TB_FLASH_META_VENDA PRIMARY KEY (ID_META),
                CONSTRAINT UK_TB_FLASH_META_VENDA UNIQUE (ID_NODO, DATA_REFERENCIA)
            )';
    END IF;
END;
-- +goose StatementEnd
-- +goose StatementBegin
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_constraints WHERE constraint_name = 'FK_TB_FLASH_META_VENDA_NODO';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'ALTER TABLE TB_FLASH_META_VENDA ADD CONSTRAINT FK_TB_FLASH_META_VENDA_NODO FOREIGN KEY (ID_NODO) REFERENCES TB_FLASH_NODO (ID_NODO)';
    END IF;
END;
-- +goose StatementEnd
-- +goose StatementBegin
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IX_TB_FLASH_META_VENDA_NODO';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX IX_TB_FLASH_META_VENDA_NODO ON TB_FLASH_META_VENDA (ID_NODO)';
    END IF;
END;
-- +goose StatementEnd
-- +goose StatementBegin
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IX_TB_FLASH_META_VENDA_DATA';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX IX_TB_FLASH_META_VENDA_DATA ON TB_FLASH_META_VENDA (DATA_REFERENCIA)';
    END IF;
END;
-- +goose StatementEnd
-- +goose StatementBegin
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IX_TB_FLASH_META_VENDA_ANOMESDIA';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX IX_TB_FLASH_META_VENDA_ANOMESDIA ON TB_FLASH_META_VENDA (ANO_REFERENCIA, MES_REFERENCIA, DIA_REFERENCIA)';
    END IF;
END;
-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_tables WHERE table_name = 'TB_FLASH_META_VENDA';
    IF v_count > 0 THEN
        EXECUTE IMMEDIATE 'DROP TABLE TB_FLASH_META_VENDA CASCADE CONSTRAINTS PURGE';
    END IF;
END;
-- +goose StatementEnd
