import { ExecutorContext } from '@nx/devkit'
import { concatFiles } from '@plugins/shared'
import { existsSync } from 'node:fs'
import { cp, mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import { ElementExecutorSchema } from './schema'

export default async function runExecutor(options: ElementExecutorSchema, context: ExecutorContext) {
	const projectConfig = context.projectsConfigurations.projects[context.projectName!]
	const outputPath = join(context.root, projectConfig.targets?.['build'].options.outputPath)

	const files = [`${outputPath}/polyfills.js`, `${outputPath}/main.js`]

	const elementPath = `${outputPath}/element`

	// Ensures directory exists
	if (!existsSync(elementPath)) {
		await mkdir(elementPath)
	}

	await concatFiles(files, `${outputPath}/element/${options.name}.js`)
	await cp(`${outputPath}/styles.css`, `${outputPath}/element/${options.name}.css`)

	// Optional static files/directories shipped alongside the element bundle
	// (e.g. the reservation manage page). Paths are relative to the workspace root.
	for (const staticPath of options.staticPaths ?? []) {
		const source = join(context.root, staticPath)
		const targetName = staticPath.split('/').pop()!
		await cp(source, join(elementPath, targetName), { recursive: true })
	}

	return { success: true }
}
