DO $body$
BEGIN

DROP TABLE IF EXISTS paineis_servicos;
DROP TABLE IF EXISTS paineis;

CREATE TABLE paineis (
    id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
    nome VARCHAR(255) NOT NULL,
    public_id VARCHAR(36) NOT NULL,
    unidade_id INT NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE painel_servicos (
    id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
    painel_id INT NOT NULL,
    servico_id INT NOT NULL,
    PRIMARY KEY (id)
);

CREATE INDEX IDX_465B1EADEDF4B99B ON paineis (unidade_id);
CREATE INDEX IDX_C253D2A29F19BCE6 ON painel_servicos (painel_id);
CREATE INDEX IDX_C253D2A282E14982 ON painel_servicos (servico_id);

ALTER TABLE paineis ADD CONSTRAINT FK_465B1EADEDF4B99B FOREIGN KEY (unidade_id) REFERENCES unidades (id) ON DELETE CASCADE;
ALTER TABLE painel_servicos ADD CONSTRAINT FK_C253D2A29F19BCE6 FOREIGN KEY (painel_id) REFERENCES paineis (id) ON DELETE CASCADE;
ALTER TABLE painel_servicos ADD CONSTRAINT FK_C253D2A282E14982 FOREIGN KEY (servico_id) REFERENCES servicos (id) ON DELETE CASCADE;

CREATE TABLE paineis_metadata (
    namespace VARCHAR(30) NOT NULL,
    name VARCHAR(30) NOT NULL,
    painel_id INT NOT NULL,
    value JSON NOT NULL,
    PRIMARY KEY (namespace, name, painel_id)
);

CREATE INDEX IDX_paineis_metadata_painel_id ON paineis_metadata (painel_id);

ALTER TABLE paineis_metadata ADD CONSTRAINT FK_paineis_metadata_painel_id FOREIGN KEY (painel_id) REFERENCES paineis (id) ON DELETE CASCADE;

END $body$;
