import fs from 'fs'
import path from 'path'

export default defineNitroPlugin(async (nitroApp) => {
    let docker = createDockerFactory('ADMIN')
    let postgres = await docker.checkContainer('postgres_12')
    if (!postgres) {
      postgres = await docker.checkAndCreateContainer({ name: 'postgres_12', img: 'postgres:12', env: ["POSTGRES_PASSWORD=postgres"], portBindings: { '5432/tcp': [{ HostPort: PgPort.toString() }] } })
      await docker.startContainer({ container: postgres })
      await sleep(3000)
    } else {
      await docker.startContainer({ container: postgres })
      await sleep(3000)
    }

    let client = await createPgClientFactory()
    let result = await executePgQuery({ client, query: "SELECT u.datname  FROM pg_catalog.pg_database u where u.datname='backend_helper';" })
    if (result.rows.length === 0) {
      await executePgQuery({ client, query: fs.readFileSync(path.resolve('./public/files/postgres/create_backend_helper.sql'), { encoding: 'utf-8'})})
      await stopPgClient(client)
      client = await createPgClientFactory('backend_helper')
      await executePgQuery({ client, query: fs.readFileSync(path.resolve('./public/files/postgres/create_user.sql'), { encoding: 'utf-8' })})
      await executePgQuery({ client, query: fs.readFileSync(path.resolve('./public/files/postgres/create_v2.sql'), { encoding: 'utf-8' })})
      await executePgQuery({ client, query: fs.readFileSync(path.resolve('./public/files/postgres/create_v1.sql'), { encoding: 'utf-8'})})
      await stopPgClient(client)
    }
})