import type { FastifyPluginAsync } from 'fastify'
import multipart from '@fastify/multipart'
import { PaginationSchema } from '@lunarfront/shared/schemas'
import { StorageFolderService, StorageFileService, StoragePermissionService } from '../../services/storage.service.js'
import { ValidationError } from '../../lib/errors.js'

export const storageRoutes: FastifyPluginAsync = async (app) => {
  await app.register(multipart, {
    limits: { fileSize: 50 * 1024 * 1024, files: 1 },
  })

  // --- Folders ---

  app.post('/storage/folders', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
    const { name, parentId, isPublic } = request.body as { name?: string; parentId?: string; isPublic?: boolean }
    if (!name?.trim()) throw new ValidationError('Folder name is required')

    // Check parent access if creating subfolder — require at least edit (not traverse or view)
    if (parentId) {
      const hasEdit = await StoragePermissionService.hasAccess(app.db, parentId, request.user.id, 'edit')
      if (!hasEdit) {
        return reply.status(403).send({ error: { message: 'No edit access to parent folder', statusCode: 403 } })
      }
    }

    const folder = await StorageFolderService.create(app.db, { name: name.trim(), parentId, isPublic, createdBy: request.user.id })
    return reply.status(201).send(folder)
  })

  app.get('/storage/folders', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const { parentId } = request.query as { parentId?: string }
    const allChildren = parentId
      ? await StorageFolderService.listChildren(app.db, parentId)
      : await StorageFolderService.listChildren(app.db, null)
    // Filter to only folders the user can access (at least traverse)
    const accessible = []
    for (const folder of allChildren) {
      const level = await StoragePermissionService.getAccessLevel(app.db, folder.id, request.user.id)
      if (level) accessible.push(folder)
    }
    return reply.send({ data: accessible })
  })

  app.get('/storage/folders/tree', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const folders = await StorageFolderService.listAllAccessible(app.db, request.user.id)
    return reply.send({ data: folders })
  })

  app.get('/storage/folders/:id', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const folder = await StorageFolderService.getById(app.db, id)
    if (!folder) return reply.status(404).send({ error: { message: 'Folder not found', statusCode: 404 } })

    const accessLevel = await StoragePermissionService.getAccessLevel(app.db, id, request.user.id)
    if (!accessLevel) return reply.status(403).send({ error: { message: 'Access denied', statusCode: 403 } })

    const breadcrumbs = await StorageFolderService.getBreadcrumbs(app.db, id)
    return reply.send({ ...folder, breadcrumbs, accessLevel })
  })

  app.patch('/storage/folders/:id', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const { name, isPublic } = request.body as { name?: string; isPublic?: boolean }

    const hasEdit = await StoragePermissionService.hasAccess(app.db, id, request.user.id, 'edit')
    if (!hasEdit) {
      return reply.status(403).send({ error: { message: 'No edit access', statusCode: 403 } })
    }

    const folder = await StorageFolderService.update(app.db, id, { name, isPublic })
    if (!folder) return reply.status(404).send({ error: { message: 'Folder not found', statusCode: 404 } })
    return reply.send(folder)
  })

  app.delete('/storage/folders/:id', { preHandler: [app.authenticate, app.requirePermission('files.delete')] }, async (request, reply) => {
    const { id } = request.params as { id: string }

    const accessLevel = await StoragePermissionService.getAccessLevel(app.db, id, request.user.id)
    if (accessLevel !== 'admin') {
      return reply.status(403).send({ error: { message: 'Admin access required', statusCode: 403 } })
    }

    const folder = await StorageFolderService.delete(app.db, id)
    if (!folder) return reply.status(404).send({ error: { message: 'Folder not found', statusCode: 404 } })
    return reply.send(folder)
  })

  // --- Folder Permissions ---

  app.get('/storage/folders/:id/permissions', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    // Only folder admins can view permission details
    const hasAdmin = await StoragePermissionService.hasAccess(app.db, id, request.user.id, 'admin')
    if (!hasAdmin) return reply.status(403).send({ error: { message: 'Admin access required', statusCode: 403 } })
    const permissions = await StoragePermissionService.listPermissions(app.db, id)
    return reply.send({ data: permissions })
  })

  app.post('/storage/folders/:id/permissions', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const { roleId, userId, accessLevel } = request.body as { roleId?: string; userId?: string; accessLevel?: string }

    const myAccess = await StoragePermissionService.getAccessLevel(app.db, id, request.user.id)
    if (myAccess !== 'admin') {
      return reply.status(403).send({ error: { message: 'Admin access required to manage permissions', statusCode: 403 } })
    }

    if (!roleId && !userId) throw new ValidationError('Either roleId or userId is required')
    if (!accessLevel || !['traverse', 'view', 'edit', 'admin'].includes(accessLevel)) throw new ValidationError('accessLevel must be traverse, view, edit, or admin')

    const perm = await StoragePermissionService.setPermission(app.db, id, roleId, userId, accessLevel)
    return reply.status(201).send(perm)
  })

  app.delete('/storage/folder-permissions/:id', { preHandler: [app.authenticate, app.requirePermission('files.delete')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    // Look up the permission to find which folder it belongs to
    // listPermissions takes folderId, we need to find by perm id — use removePermission which fetches first
    const perm = await StoragePermissionService.getPermissionById(app.db, id)
    if (!perm) return reply.status(404).send({ error: { message: 'Permission not found', statusCode: 404 } })

    // Verify admin access on the folder this permission belongs to
    const hasAdmin = await StoragePermissionService.hasAccess(app.db, perm.folderId, request.user.id, 'admin')
    if (!hasAdmin) return reply.status(403).send({ error: { message: 'Admin access required', statusCode: 403 } })

    const deleted = await StoragePermissionService.removePermission(app.db, id)
    return reply.send(deleted)
  })

  // --- Files ---

  app.post('/storage/folders/:folderId/files', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
    const { folderId } = request.params as { folderId: string }

    const hasEdit = await StoragePermissionService.hasAccess(app.db, folderId, request.user.id, 'edit')
    if (!hasEdit) {
      return reply.status(403).send({ error: { message: 'No edit access to this folder', statusCode: 403 } })
    }

    const data = await request.file()
    if (!data) throw new ValidationError('No file provided')

    const buffer = await data.toBuffer()

    const file = await StorageFileService.upload(app.db, app.storage, {
      folderId,
      data: buffer,
      filename: data.filename,
      contentType: data.mimetype,
      uploadedBy: request.user.id,
    })

    return reply.status(201).send(file)
  })

  app.get('/storage/folders/:folderId/files', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const { folderId } = request.params as { folderId: string }

    // traverse only allows navigating folders, not viewing files
    const accessLevel = await StoragePermissionService.getAccessLevel(app.db, folderId, request.user.id)
    if (!accessLevel || accessLevel === 'traverse') return reply.status(403).send({ error: { message: 'Access denied', statusCode: 403 } })

    const params = PaginationSchema.parse(request.query)
    const result = await StorageFileService.listByFolder(app.db, folderId, params)
    return reply.send(result)
  })

  app.delete('/storage/files/:id', { preHandler: [app.authenticate, app.requirePermission('files.delete')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const file = await StorageFileService.getById(app.db, id)
    if (!file) return reply.status(404).send({ error: { message: 'File not found', statusCode: 404 } })

    const hasEdit = await StoragePermissionService.hasAccess(app.db, file.folderId, request.user.id, 'edit')
    if (!hasEdit) {
      return reply.status(403).send({ error: { message: 'No edit access', statusCode: 403 } })
    }

    const deleted = await StorageFileService.delete(app.db, app.storage, id)
    return reply.send(deleted)
  })

  app.get('/storage/files/:id/signed-url', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const { id } = request.params as { id: string }
    const file = await StorageFileService.getById(app.db, id)
    if (!file) return reply.status(404).send({ error: { message: 'File not found', statusCode: 404 } })

    const hasView = await StoragePermissionService.hasAccess(app.db, file.folderId, request.user.id, 'view')
    if (!hasView) return reply.status(403).send({ error: { message: 'Access denied', statusCode: 403 } })

    const token = app.jwt.sign({ path: file.path, purpose: 'file-access' } as any, { expiresIn: '15m' })
    const signedUrl = `/v1/files/s/${file.path}?token=${token}`
    return reply.send({ url: signedUrl })
  })

  app.get('/storage/files/search', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
    const { q } = request.query as { q?: string }
    if (!q) return reply.send({ data: [], pagination: { page: 1, limit: 25, total: 0, totalPages: 0 } })

    const params = PaginationSchema.parse(request.query)
    const result = await StorageFileService.search(app.db, q, params)

    // Filter results to only files the user has at least view access to
    const filtered = []
    for (const file of result.data) {
      const hasView = await StoragePermissionService.hasAccess(app.db, (file as any).folderId, request.user.id, 'view')
      if (hasView) filtered.push(file)
    }

    return reply.send({ data: filtered, pagination: { ...result.pagination, total: filtered.length } })
  })
}
