import type { FastifyInstance } from 'fastify'
import { z } from 'zod'
import { logEvent } from '../db/index.js'
import { startTransfer, getTransfer, listTransfers, cancelTransfer } from '../ssh/transfer.js'

const startSchema = z.object({
  sourceIntegrationId: z.number().int().positive(),
  destIntegrationId: z.number().int().positive(),
  sourcePaths: z.array(z.string().min(1)).min(1),
  destPath: z.string().min(1),
  move: z.boolean().optional(),
})

export async function transferRoutes(app: FastifyInstance) {
  app.addHook('onRequest', app.authenticate)

  app.post('/api/transfers', async (req, reply) => {
    const parsed = startSchema.safeParse(req.body)
    if (!parsed.success) {
      return reply.code(400).send({ error: parsed.error.issues[0]?.message ?? 'Invalid input' })
    }
    const transferId = startTransfer(parsed.data)
    logEvent(
      'host_transfer_started',
      `${parsed.data.move ? 'Move' : 'Copy'} of ${parsed.data.sourcePaths.length} item(s) between hosts`,
      'ssh',
    )
    return reply.code(201).send({ transferId })
  })

  app.get('/api/transfers', async () => {
    return { transfers: listTransfers() }
  })

  app.get('/api/transfers/:id', async (req, reply) => {
    const id = (req.params as { id: string }).id
    const transfer = getTransfer(id)
    if (!transfer) return reply.code(404).send({ error: 'Transfer not found' })
    return transfer
  })

  app.post('/api/transfers/:id/cancel', async (req, reply) => {
    const id = (req.params as { id: string }).id
    const ok = cancelTransfer(id)
    if (!ok) return reply.code(409).send({ error: 'Transfer is not running' })
    return { ok: true }
  })
}
