import { i18n } from './i18n'
import { sdk } from './sdk'
import { uiPort } from './utils'

/**
 * Main daemon definition.
 *
 * Mounts the `main` volume at /data (same contract as 0.3.5) and runs the
 * container's ENTRYPOINT (docker_entrypoint.sh -> Next.js standalone).
 *
 * Readiness: we check the listening port rather than hitting /api/health
 * because the Next.js server starts listening before Prisma has warmed up;
 * the entrypoint's own DB seeding logic is responsible for DB readiness.
 * If you want a stricter gate later, switch to `sdk.healthCheck.checkWebUrl`
 * pointed at `http://localhost:3000/api/health` and look for `status: ok`.
 */
export const main = sdk.setupMain(async ({ effects }) => {
  console.info(i18n('Starting Proof of Work'))

  return sdk.Daemons.of(effects).addDaemon('main', {
    subcontainer: await sdk.SubContainer.of(
      effects,
      { imageId: 'main' },
      sdk.Mounts.of().mountVolume({
        volumeId: 'main',
        subpath: null,
        mountpoint: '/data',
        readonly: false,
      }),
      'proof-of-work-main',
    ),
    exec: { command: sdk.useEntrypoint() },
    ready: {
      display: i18n('Web Interface'),
      fn: () =>
        sdk.healthCheck.checkPortListening(effects, uiPort, {
          successMessage: i18n('The web interface is ready'),
          errorMessage: i18n('The web interface is not ready'),
        }),
    },
    requires: [],
  })
})
