START TRANSACTION;

CREATE TYPE campaign_status AS ENUM ('ACTIVE', 'CLOSED');

CREATE TABLE campaign (
    id BIGSERIAL PRIMARY KEY,
    key short_text NOT NULL,
    name short_text NOT NULL,
    status campaign_status NOT NULL,
    start_date DATE NOT NULL,
    deleted BOOLEAN NOT NULL DEFAULT FALSE
);

CREATE UNIQUE INDEX campaign_unique_name_constraint ON campaign (name)
    WHERE deleted IS NOT TRUE;

CREATE UNIQUE INDEX campaign_unique_key_constraint ON campaign (key)
    WHERE deleted IS NOT TRUE;

CREATE UNIQUE INDEX campaign_unique_start_date_constraint ON campaign (start_date)
    WHERE deleted IS NOT TRUE;

CREATE INDEX campaign_deleted_index ON campaign (deleted);

CREATE TABLE campaign_big_order (
    id BIGSERIAL PRIMARY KEY,
    campaign_id BIGINT NOT NULL REFERENCES campaign (id) ON UPDATE CASCADE ON DELETE CASCADE,
    big_order_id BIGINT NOT NULL REFERENCES bot_big_order (id) ON UPDATE CASCADE ON DELETE CASCADE,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    UNIQUE (campaign_id, big_order_id)
);

INSERT INTO campaign (key, name, status, start_date) VALUES ('aug2018', 'Заявки на железо, август 2018', 'CLOSED', '2018-08-01');
INSERT INTO campaign (key, name, status, start_date) VALUES ('aug2019', 'Заявки на железо, август 2019', 'CLOSED', '2019-08-01');

INSERT INTO campaign_big_order (campaign_id, big_order_id) (SELECT c.id as campaign_id, bo.id as big_order_id FROM campaign c, bot_big_order bo WHERE c.key = 'aug2018' and bo.id = 37);
INSERT INTO campaign_big_order (campaign_id, big_order_id) (SELECT c.id as campaign_id, bo.id as big_order_id FROM campaign c, bot_big_order bo WHERE c.key = 'aug2019' and bo.id = 39);
INSERT INTO campaign_big_order (campaign_id, big_order_id) (SELECT c.id as campaign_id, bo.id as big_order_id FROM campaign c, bot_big_order bo WHERE c.key = 'aug2019' and bo.id = 40);
INSERT INTO campaign_big_order (campaign_id, big_order_id) (SELECT c.id as campaign_id, bo.id as big_order_id FROM campaign c, bot_big_order bo WHERE c.key = 'aug2019' and bo.id = 41);

COMMIT;