import {
  describe
  , expect
  , it
  , beforeEach
} from 'bun:test'
import {
  Elysia
} from 'elysia'
import {
  treaty
} from '@elysiajs/eden'
import app from '../app.ts'
import Docker from 'dockerode'


if (!process.env.WL_FILE_PATH) throw new Error("WL_FILE_PATH is missing in env");
if (!process.env.WL_USERNAME) throw new Error("WL_USERNAME is missing in env.");
if (!process.env.WL_PASSWORD) throw new Error("WL_PASSWORD is missing in env.");

const whitelistFilePath = process.env.WL_FILE_PATH!
const fixture = "3aa5ad5e62eaffd148cff3dbe93ff2e1e9cbcf01"


const username = process.env.WL_USERNAME!
const password = process.env.WL_PASSWORD!
const opts = {
  headers: {
    authorization: "Basic " + btoa(username + ':' + password)
  }
}
const api = treaty(app)



describe
  ('tracker-helper', () => {


    beforeEach(() => {
      let whitelistFilePath = process.env.WL_FILE_PATH!
      console.log(`Asserting existance of whitelist at ${whitelistFilePath}`)
      // create whitelist file if it doesn't exist
      const assertWhitelistExists = async function assertWhitelistExists(whitelistFilePath: string) {
        const wlFile = Bun.file(whitelistFilePath);
        const exists = await wlFile.exists()
        if (!exists) {
          console.log(`creating whitelist file at ${whitelistFilePath}`)
          await wlFile.write("")
        }
      }
      const clearWhitelist = async function clearWhitelist(whitelistFilePath: string) {
        const wlFile = Bun.file(whitelistFilePath);
        await wlFile.write("")
      }
      assertWhitelistExists(whitelistFilePath)
      clearWhitelist(whitelistFilePath)
    });

    it('return a health response', async () => {
      const { data, status } = await api.health.get()
      expect(status).toBe(200)
      expect(data).toBe("OK")
    })

    it('return a version', async () => {
      const { data, status } = await api.version.get(opts)
      expect(status).toBe(200)
      expect(data).toContain("version")
    })

    it('return a whitelist', async () => {
      const seedWhitelist = async function clearWhitelist(p: string, f: string) {
        const wlFile = Bun.file(p);
        await wlFile.write(f)
      }
      await seedWhitelist(whitelistFilePath, fixture)
      const { data, status } = await api.whitelist.get(opts)
      expect(status).toBe(200)
      expect(data).toContain("3aa5ad5e62eaffd148cff3dbe93ff2e1e9cbcf01")
    })

    it('expects the whitelist to already exist', async () => {
      const whitelist = Bun.file(whitelistFilePath)
      const whitelistExists = await whitelist.exists()
      expect(whitelistExists).toBe(true)
    })

    it('appends a new info_hash to the whitelist file', async () => {


      // make an api call which is supposed to add an entry to the whitelist
      const { data, status } = await api.whitelist.post(fixture, opts)

      // assert that the entry has been added to the whitelist


      const w = Bun.file(whitelistFilePath)
      const whitelistAfter = await w.text()
      console.log('whitelistAfter as follows')
      console.log(whitelistAfter)

      expect(status).toBe(201)
      expect(data).toMatch(fixture)
      expect(whitelistAfter).toMatch(fixture)

    })

    // it('sends a SIGHUP to opentracker', async () => {

    //   const { data, status } = await api.whitelist.post(fixture, opts)
    //   const containerId = "act-ci-Tests-Checks-6e6f12196682961041a41a25b9d0dcf00e4d0f8e58f-7cb37eebfe9e1670328d58ad1f7c7bdf0fa078298ca6dd299e67d0141a4b9579"
    //   // await docker.getContainer(containerId).kill({ signal: 'SIGHUP' })
    //   let container = await docker.getContainer(containerId)
    //   container.inspect

    // })


    // // This is skipped because I couldn't figure out opentracker's whitelist add/delete via FIFO functionality.
    // // I got as far as writing to the FIFO, and seeing opentracker acknowledge the line in it's logs.
    // // Despite this, requests from qbittorrent to opentracker responded with, 
    // // "Requested download is not authorized for use with this tracker"
    // // About a week on this problem, and I give up! Using the whitelist reloading strat instead.
    // it.skip('writes a new info_hash to a fifo', async () => {
    //   const fifoFilePath = process.env.WL_FIFO_PATH!
    //   const fifo = Bun.file(fifoFilePath)
    //   const fifoExists = await fifo.exists();


    //   // create fifo if it doesn't exist
    //   if (!fifoExists) {
    //     await Bun.spawn(["mkfifo", fifoFilePath]).exited;
    //   }

    //   // Start a process to read from the FIFO
    //   const reader = Bun.spawn(["cat", fifoFilePath], { stdout: "pipe" });

    //   const { data, status } = await api.whitelist.post("3aa5ad5e62eaffd148cff3dbe93ff2e1e9cbcf01", opts)

    //   const text = await new Response(reader.stdout).text();

    //   expect(text).toBe("3aa5ad5e62eaffd148cff3dbe93ff2e1e9cbcf01\n")
    //   expect(status).toBe(200)
    //   expect(data).toBe("3aa5ad5e62eaffd148cff3dbe93ff2e1e9cbcf01")
    // })

    it('returns 401 when username/password is missing from GET /whitelist ', async () => {
      const { status } = await api.whitelist.get()
      expect(status).toBe(401)
    })

    it('returns 401 when username/password is missing from POST /whitelist ', async () => {
      const { status } = await api.whitelist.post()
      expect(status).toBe(401)
    })

  })