import { execFileSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import path from 'node:path'

const VITE_MANIFEST_PATH = path.join(process.cwd(), 'public', 'build', 'manifest.json')

function ensureCompiledAssets() {
  if (existsSync(VITE_MANIFEST_PATH)) {
    return
  }

  const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm'

  execFileSync(npmCommand, ['run', 'build'], {
    cwd: process.cwd(),
    stdio: 'inherit',
  })
}

function warmBladeViews() {
  execFileSync('php', ['artisan', 'view:clear'], {
    cwd: process.cwd(),
    stdio: 'inherit',
  })

  execFileSync('php', ['artisan', 'view:cache'], {
    cwd: process.cwd(),
    stdio: 'inherit',
  })
}

export default async function globalSetup() {
  ensureCompiledAssets()
  warmBladeViews()
}