import { dialog, ipcMain } from 'electron'
import { runStreamed } from '../commandRunner'

export function registerCreateIpc(): void {
  ipcMain.handle('create:pickDirectory', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory', 'createDirectory']
    })
    return result.canceled ? null : result.filePaths[0]
  })

  ipcMain.handle(
    'create:configure',
    (
      event,
      operationId: string,
      directory: string,
      projectName: string,
      projectType: string,
      docroot: string
    ) => {
      const args = ['config', `--project-name=${projectName}`, '--auto']
      if (projectType) args.push(`--project-type=${projectType}`)
      if (docroot.trim()) args.push(`--docroot=${docroot.trim()}`)
      return runStreamed(operationId, args, event.sender, { cwd: directory })
    }
  )

  // `ddev config --project-type=wordpress` only scaffolds the DDEV-managed
  // wp-config.php bridge and wp-content/uploads — it doesn't download
  // WordPress core (wp-admin, wp-includes, index.php, etc.), and even with
  // core downloaded the site has no database tables until `wp core install`
  // runs. Both require the project to be started, since wp-cli runs inside
  // the web container. Kept as two separate tracked operations rather than
  // one combined command so each phase's terminal:exit event correctly owns
  // its own status-bar/toast lifecycle (see useCreateProject.ts).
  ipcMain.handle(
    'create:downloadWordpress',
    (event, operationId: string, directory: string, locale: string) => {
      const args = ['wp', 'core', 'download']
      if (locale.trim() && locale.trim() !== 'en_US') args.push(`--locale=${locale.trim()}`)
      return runStreamed(operationId, args, event.sender, { cwd: directory })
    }
  )

  ipcMain.handle(
    'create:setupWordpress',
    (
      event,
      operationId: string,
      directory: string,
      siteUrl: string,
      title: string,
      adminUser: string,
      adminPassword: string,
      adminEmail: string,
      multisite: 'none' | 'subdirectory' | 'subdomain'
    ) => {
      const args = [
        'wp',
        'core',
        multisite === 'none' ? 'install' : 'multisite-install',
        `--url=${siteUrl}`,
        `--title=${title}`,
        `--admin_user=${adminUser}`,
        `--admin_password=${adminPassword}`,
        `--admin_email=${adminEmail}`,
        '--skip-email'
      ]
      if (multisite === 'subdomain') args.push('--subdomains')
      return runStreamed(operationId, args, event.sender, { cwd: directory })
    }
  )
}
