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}`)
      // ddev creates a missing docroot automatically (--create-docroot is a
      // deprecated no-op as of DDEV v1.25) — Drupal's docroot ('web') gets
      // created here, ahead of the composer install that populates it.
      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 })
    }
  )

  // Same class of gap as WordPress: `ddev config --project-type=drupal*`
  // only writes DDEV's settings.php bridge, not Drupal core — that's what
  // was producing the 403 (empty docroot, nothing for the webserver to
  // serve). `drupal/recommended-project`'s own composer.json places core
  // under web/ via installer-paths, so this runs from the project root
  // (matching the --docroot=web set by create:configure), not inside web/.
  ipcMain.handle('create:downloadDrupal', (event, operationId: string, directory: string) =>
    runStreamed(
      operationId,
      ['composer', 'create-project', 'drupal/recommended-project'],
      event.sender,
      { cwd: directory }
    )
  )

  // drush was dropped from drupal/recommended-project's default
  // dependencies in recent Drupal releases, so `drush site:install` has
  // nothing to run without adding it explicitly first.
  ipcMain.handle('create:requireDrush', (event, operationId: string, directory: string) =>
    runStreamed(operationId, ['composer', 'require', 'drush/drush'], event.sender, {
      cwd: directory
    })
  )

  ipcMain.handle(
    'create:setupDrupal',
    (
      event,
      operationId: string,
      directory: string,
      siteName: string,
      adminUser: string,
      adminPassword: string,
      adminEmail: string,
      profile: string
    ) => {
      const args = [
        'drush',
        'site:install',
        profile || 'standard',
        `--site-name=${siteName}`,
        `--account-name=${adminUser}`,
        `--account-pass=${adminPassword}`,
        `--account-mail=${adminEmail}`,
        '-y'
      ]
      return runStreamed(operationId, args, event.sender, { cwd: directory })
    }
  )
}
