DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'payment_titles_type_valid'
  ) THEN
    ALTER TABLE payment_titles
      ADD CONSTRAINT payment_titles_type_valid CHECK (
        payment_type IN ('subscription', 'bill', 'one_time', 'income', 'any')
      );
  END IF;
END $$;

INSERT INTO payment_titles (
  user_id,
  name,
  normalized_name,
  payment_type,
  created_at,
  updated_at
)
SELECT DISTINCT
  user_id,
  title,
  LOWER(REGEXP_REPLACE(TRIM(title), '\s+', ' ', 'g')),
  'income',
  NOW()::text,
  NOW()::text
FROM income
WHERE TRIM(title) <> ''
ON CONFLICT (user_id, normalized_name, payment_type) DO NOTHING;
