BEGIN;

CREATE TABLE kandang_groups (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    status VARCHAR(20) NOT NULL,
    location_id BIGINT NOT NULL REFERENCES locations (id) ON DELETE RESTRICT ON UPDATE CASCADE,
    pic_id BIGINT REFERENCES users (id) ON DELETE SET NULL ON UPDATE CASCADE,
    created_at TIMESTAMPTZ DEFAULT NOW (),
    updated_at TIMESTAMPTZ DEFAULT NOW (),
    deleted_at TIMESTAMPTZ,
    created_by BIGINT REFERENCES users (id) ON DELETE SET NULL ON UPDATE CASCADE
);

CREATE UNIQUE INDEX kandang_groups_name_unique ON kandang_groups (name)
WHERE
    deleted_at IS NULL;

ALTER TABLE kandangs
    ADD COLUMN kandang_group_id BIGINT;

CREATE TEMP TABLE tmp_kandang_group_map (
    kandang_id BIGINT PRIMARY KEY,
    kandang_group_id BIGINT NOT NULL
) ON COMMIT DROP;

INSERT INTO tmp_kandang_group_map (kandang_id, kandang_group_id)
SELECT
    k.id,
    nextval(pg_get_serial_sequence('kandang_groups', 'id'))
FROM kandangs k
ORDER BY
    k.id;

INSERT INTO kandang_groups (
    id,
    name,
    status,
    location_id,
    pic_id,
    created_at,
    updated_at,
    deleted_at,
    created_by
)
SELECT
    m.kandang_group_id,
    k.name,
    k.status,
    k.location_id,
    CASE WHEN pic.id IS NOT NULL THEN k.pic_id ELSE NULL END,
    k.created_at,
    k.updated_at,
    k.deleted_at,
    CASE WHEN creator.id IS NOT NULL THEN k.created_by ELSE NULL END
FROM kandangs k
         JOIN tmp_kandang_group_map m ON m.kandang_id = k.id
         LEFT JOIN users pic ON pic.id = k.pic_id
         LEFT JOIN users creator ON creator.id = k.created_by
ORDER BY
    k.id;

UPDATE kandangs k
SET kandang_group_id = m.kandang_group_id
FROM tmp_kandang_group_map m
WHERE
    m.kandang_id = k.id;

ALTER TABLE daily_checklists
    DROP CONSTRAINT IF EXISTS fk_daily_checklists_kandang;

UPDATE daily_checklists dc
SET kandang_id = m.kandang_group_id
FROM tmp_kandang_group_map m
WHERE
    dc.kandang_id = m.kandang_id;

ALTER TABLE daily_checklists
    ADD CONSTRAINT fk_daily_checklists_kandang
        FOREIGN KEY (kandang_id) REFERENCES kandang_groups (id) ON DELETE CASCADE;

ALTER TABLE kandangs
    ALTER COLUMN kandang_group_id SET NOT NULL;

ALTER TABLE kandangs
    ADD CONSTRAINT fk_kandangs_kandang_group
        FOREIGN KEY (kandang_group_id) REFERENCES kandang_groups (id) ON DELETE RESTRICT ON UPDATE CASCADE;

CREATE INDEX idx_kandangs_kandang_group_id ON kandangs (kandang_group_id);

COMMIT;
