BEGIN;

--
-- Add table for flow params
--


CREATE TABLE IF NOT EXISTS "flow_params" (
    "id" bigserial not null primary key ,
    "name" character varying(100) NOT NULL,
    "label" text NOT NULL,
    "type" character varying(100) NOT NULL,
    "default_value" text,
    "enabled" boolean NOT NULL DEFAULT true,
    "mandatory" boolean NOT NULL DEFAULT false,
    "values" json NOT NULL DEFAULT '[]'::json,
    "order" integer NOT NULL);

    --
    -- Table: templates
    --

CREATE TABLE IF NOT EXISTS "templates" (
    "id" bigserial NOT NULL primary key,
    "name" varchar(255) unique);

--
-- Table: template_rules
--

CREATE TABLE IF NOT EXISTS "template_rules" (
    "id" bigserial NOT NULL primary key,
    "tpl_id" bigint,
    "name" varchar(255),
    "rule_mode" varchar(255),
    "rule_when" text,
    "rule_order" integer
    );

-- Table: template_tasks
--

CREATE TABLE IF NOT EXISTS "template_tasks" (
    "id" bigserial NOT NULL primary key,
    "rule_id" bigint,
    "task_where" varchar(255),
    "task_when" varchar(255),
    "task_order" int,
    "type" varchar(255),
    "task_path" text,
    "task_delay" int,
    "task_condition" text
    );


DO $$
BEGIN
	BEGIN
		ALTER TABLE "flows" RENAME COLUMN "template" TO tpl_name;
	END;
END;
$$;

--
-- flow.template : Reference on template id
--

DO $$
BEGIN
	BEGIN
		ALTER TABLE "flows" ADD COLUMN template bigint DEFAULT 0;
	END;
END;
$$;

INSERT INTO templates (name) SELECT DISTINCT tpl_name from flows;

UPDATE flows SET template = (SELECT id from templates WHERE flows.tpl_name = templates.name);

DO $$
BEGIN
	BEGIN
		ALTER TABLE "flows" DROP COLUMN tpl_name;
	END;
END;
$$;


DO $$
BEGIN
	BEGIN
		ALTER TABLE "flows" ADD COLUMN active boolean DEFAULT TRUE;
	EXCEPTION
			WHEN duplicate_column THEN
			-- do nothing
	END;
END;
$$;


--
-- Fixes type of partner.site_id
--

DO $$
BEGIN
	BEGIN
    ALTER TABLE "partners" RENAME COLUMN site_id TO old_site;
  END;
END;
$$;

DO $$
BEGIN
	BEGIN
		ALTER TABLE "partners" ADD COLUMN site_id bigint DEFAULT null;
  END;
END;
$$;

UPDATE partners SET site_id = CAST(partners.old_site AS bigint);

DO $$
BEGIN
	BEGIN
		ALTER TABLE "partners" DROP COLUMN old_site;
	END;
END;
$$;
COMMIT;
