ALTER TABLE expense_items ADD COLUMN IF NOT EXISTS item VARCHAR(255) NOT NULL DEFAULT '';

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'expenses'
          AND column_name = 'expense_name'
    ) THEN
        UPDATE expense_items ei
        SET item = e.expense_name
        FROM expenses e
        WHERE ei.expense_id = e.id
          AND COALESCE(ei.item, '') = '';
    END IF;
END $$;

DROP INDEX IF EXISTS idx_expenses_expense_name;
ALTER TABLE expenses DROP COLUMN IF EXISTS expense_name;
CREATE INDEX IF NOT EXISTS idx_expense_items_item ON expense_items(item);
