BEGIN;

ALTER TABLE daily_checklists
    ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS deleted_by BIGINT;

CREATE INDEX IF NOT EXISTS idx_daily_checklists_deleted_at
    ON daily_checklists (deleted_at);
CREATE INDEX IF NOT EXISTS idx_daily_checklists_deleted_by
    ON daily_checklists (deleted_by);

ALTER TABLE daily_checklists
    DROP CONSTRAINT IF EXISTS fk_daily_checklists_deleted_by,
    ADD CONSTRAINT fk_daily_checklists_deleted_by
        FOREIGN KEY (deleted_by) REFERENCES users(id) ON DELETE SET NULL;

ALTER TABLE daily_checklists
    DROP CONSTRAINT IF EXISTS daily_checklists_date_kandang_category_key;

DROP INDEX IF EXISTS idx_daily_checklists_unique_non_rejected;

CREATE UNIQUE INDEX IF NOT EXISTS idx_daily_checklists_unique_non_rejected
    ON daily_checklists (date, kandang_id, category)
    WHERE (status IS NULL OR status <> 'REJECTED')
      AND deleted_at IS NULL;

COMMIT;
