import { ipcMain } from 'electron'
import { describeProject, listProjects } from '../ddev'
import { runStreamed } from '../commandRunner'

export function registerProjectsIpc(): void {
  ipcMain.handle('projects:list', () => listProjects())
  ipcMain.handle('projects:describe', (_event, name: string) => describeProject(name))
  ipcMain.handle('projects:start', (event, operationId: string, name: string) =>
    runStreamed(operationId, ['start', name], event.sender)
  )
  ipcMain.handle('projects:stop', (event, operationId: string, name: string) =>
    runStreamed(operationId, ['stop', name], event.sender)
  )
  // `-y` matters here beyond convenience: we spawn `ddev` with no stdin
  // wired up (see commandRunner.ts), so any confirmation prompt ddev tries
  // to show — e.g. when a database type change requires it — would hang the
  // operation forever with no way for the user to answer it.
  ipcMain.handle('projects:restart', (event, operationId: string, name: string) =>
    runStreamed(operationId, ['restart', name, '-y'], event.sender)
  )
  // Removes DDEV's project registration + containers + database (auto-
  // snapshotted first, unless omitted) — does not touch the project's files
  // on disk.
  ipcMain.handle('projects:delete', (event, operationId: string, name: string) =>
    runStreamed(operationId, ['delete', name, '--yes'], event.sender)
  )

  // Reconfigures a project's PHP version, web server, database, or Xdebug
  // state via `ddev config` (writes .ddev/config.yaml) — callers are
  // expected to follow a successful call with a restart (if the project is
  // running) to actually apply it, same two-phase pattern as create.ts.
  ipcMain.handle(
    'projects:updateEnvironment',
    (
      event,
      operationId: string,
      name: string,
      approot: string,
      updates: {
        phpVersion?: string
        webserverType?: string
        database?: string
        xdebugEnabled?: boolean
      }
    ) => {
      const args = ['config', `--project-name=${name}`]
      if (updates.phpVersion) args.push(`--php-version=${updates.phpVersion}`)
      if (updates.webserverType) args.push(`--webserver-type=${updates.webserverType}`)
      if (updates.database) args.push(`--database=${updates.database}`)
      if (updates.xdebugEnabled !== undefined) {
        args.push(`--xdebug-enabled=${updates.xdebugEnabled}`)
      }
      return runStreamed(operationId, args, event.sender, { cwd: approot })
    }
  )
}
