ALTER TABLE shares
  ADD COLUMN IF NOT EXISTS share_kind text NOT NULL DEFAULT 'single';

ALTER TABLE shares
  ADD COLUMN IF NOT EXISTS pack_name text;

ALTER TABLE shares
  ALTER COLUMN resource_type DROP NOT NULL;

ALTER TABLE shares
  DROP CONSTRAINT IF EXISTS shares_resource_type_check;

ALTER TABLE shares
  DROP CONSTRAINT IF EXISTS shares_kind_check;

ALTER TABLE shares
  DROP CONSTRAINT IF EXISTS shares_shape_check;

ALTER TABLE shares
  ADD CONSTRAINT shares_resource_type_check CHECK (
    resource_type IS NULL OR resource_type IN ('program', 'workoutTemplate')
  );

ALTER TABLE shares
  ADD CONSTRAINT shares_kind_check CHECK (share_kind IN ('single', 'pack'));

ALTER TABLE shares
  ADD CONSTRAINT shares_shape_check CHECK (
    (
      share_kind = 'single'
      AND resource_type IN ('program', 'workoutTemplate')
      AND pack_name IS NULL
    )
    OR
    (
      share_kind = 'pack'
      AND resource_type IS NULL
      AND length(trim(pack_name)) > 0
      AND COALESCE(jsonb_typeof(payload_json -> 'items') = 'array', false)
      AND jsonb_array_length(payload_json -> 'items') > 0
    )
  );
