# frozen_string_literal: true

# License: AGPL-3.0-or-later WITH WTO-AP-3.0-or-later
# Full license explanation at https://github.com/houdiniproject/houdini/blob/main/LICENSE
require 'rails_helper'

Rails.application.load_tasks

describe 'js.rake' do # rubocop:disable RSpec/DescribeClass
	def system!(*args)
		system(*args) || abort("\n== Command #{args} failed ==")
	end

	let(:js_dir) { Rails.root.join('app/javascript') }

	def wrap_task(rake_taskname)
		task = Rake::Task[rake_taskname]
		Rake.application.tasks.each(&:reenable)
		task.invoke
		yield
		Rake.application.tasks.each(&:reenable)
	end

	def verify_cleaned(rake_taskname) # rubocop:disable Metrics/AbcSize
		wrap_task(rake_taskname) do
			expect(!File.exist?(js_dir.join('routes.js'))).to(
				be(true),
				"#{js_dir.join('routes.js')} wasn't cleaned by bin/rails #{rake_taskname}"
			)

			expect(!File.exist?(js_dir.join('routes.d.ts'))).to(
				be(true),
				"#{js_dir.join('routes.d.ts')} wasn't cleaned by bin/rails #{rake_taskname}"
			)
		end
	end

	def verify_task_generate(rake_taskname)
		wrap_task(rake_taskname) do
			expect(File.exist?(js_dir.join('routes.js'))).to(
				be(true),
				"#{js_dir.join('routes.js')} wasn't generated by bin/rails #{rake_taskname}"
			)

			expect(File.exist?(js_dir.join('routes.d.ts'))).to(
				be(true),
				"#{js_dir.join('routes.d.ts')} wasn't generated by bin/rails #{rake_taskname}"
			)
		end
	end

	it 'export and clean' do # rubocop:disable RSpec/NoExpectationExample
		verify_task_generate('js:routes:typescript')
		verify_cleaned('js:routes:clean')
	end
end
