-- add the generated id to watermark_configuration table
alter table watermark_configuration
    add column id BIGINT GENERATED ALWAYS AS IDENTITY;
alter table watermark_configuration
    add column name          VARCHAR(255),
    add column enabled       BOOLEAN DEFAULT TRUE,
    add column created_by    VARCHAR(255),
    add column date_added    TIMESTAMP WITHOUT TIME ZONE,
    add column date_modified TIMESTAMP WITHOUT TIME ZONE;
--initialise the new columns for the current watermark configurations
update watermark_configuration
set name    = 'Watermark ' || id,
    enabled = true;

-- update the primary key constraint based on the new configuration and add the foreign key contraints to the dossier and dossier_template tables
alter table watermark_configuration
    drop constraint watermark_configuration_pkey;
alter table watermark_configuration
    add constraint watermark_configuration_pkey PRIMARY KEY (id);
delete
from watermark_configuration
where dossier_template_id not in (select id from dossier_template);
alter table watermark_configuration
    add constraint watermark_dossier_template_id_fk FOREIGN KEY (dossier_template_id) REFERENCES dossier_template (id);
-- add the link to watermark_configuration to dossier table and the foreign key contraints
alter table dossier
    add column watermark_id BIGINT;
alter table dossier
    add column preview_watermark_id BIGINT;
alter table dossier
    add constraint watermark_id_fk FOREIGN KEY (watermark_id) REFERENCES watermark_configuration (id);
alter table dossier
    add constraint preview_watermark_id_fk FOREIGN KEY (preview_watermark_id) REFERENCES watermark_configuration (id);
-- update the dossier table with the corresponding watermark based on the dossier template given
update dossier d
set watermark_id = (select id from watermark_configuration w where w.dossier_template_id = d.dossier_template_id)
where d.watermark_enabled = true;
update dossier d
set preview_watermark_id = (select id from watermark_configuration w where w.dossier_template_id = d.dossier_template_id)
where d.watermark_preview_enabled = true;
-- remove the previous columns, not needed anymore
alter table dossier
    drop column watermark_enabled;
alter table dossier
    drop column watermark_preview_enabled;
