const express = require('express')
const { z } = require('zod')
const {
  findUserProfileById,
  followUser,
  unfollowUser,
  listPublicTierListsByAuthor,
  listFollowingTierLists,
} = require('../db')
const { requireAuth } = require('../middleware/auth')

const router = express.Router()

router.get('/following-feed', requireAuth, async (req, res) => {
  const schema = z.object({
    q: z.string().trim().max(120).optional().default(''),
  })
  const parsed = schema.safeParse(req.query)
  if (!parsed.success) return res.status(400).json({ error: 'bad_request' })

  const tierLists = await listFollowingTierLists(req.session.userId, parsed.data.q)
  res.json({ tierLists })
})

router.get('/:userId', async (req, res) => {
  const user = await findUserProfileById(req.params.userId, req.session?.userId || '')
  if (!user) return res.status(404).json({ error: 'not_found' })
  res.json({ user })
})

router.get('/:userId/tierlists', async (req, res) => {
  const schema = z.object({
    q: z.string().trim().max(120).optional().default(''),
  })
  const parsed = schema.safeParse(req.query)
  if (!parsed.success) return res.status(400).json({ error: 'bad_request' })

  const user = await findUserProfileById(req.params.userId, req.session?.userId || '')
  if (!user) return res.status(404).json({ error: 'not_found' })

  const tierLists = await listPublicTierListsByAuthor(
    req.params.userId,
    req.session?.userId || '',
    parsed.data.q
  )
  res.json({ tierLists })
})

router.post('/:userId/follow', requireAuth, async (req, res) => {
  const targetUserId = req.params.userId || ''
  if (!targetUserId || targetUserId === req.session.userId) {
    return res.status(400).json({ error: 'self_follow_not_allowed' })
  }

  const user = await findUserProfileById(targetUserId, req.session.userId)
  if (!user) return res.status(404).json({ error: 'not_found' })

  await followUser({ followerId: req.session.userId, followingId: targetUserId })
  const updated = await findUserProfileById(targetUserId, req.session.userId)
  res.json({ user: updated })
})

router.delete('/:userId/follow', requireAuth, async (req, res) => {
  const targetUserId = req.params.userId || ''
  if (!targetUserId || targetUserId === req.session.userId) {
    return res.status(400).json({ error: 'self_follow_not_allowed' })
  }

  const user = await findUserProfileById(targetUserId, req.session.userId)
  if (!user) return res.status(404).json({ error: 'not_found' })

  await unfollowUser({ followerId: req.session.userId, followingId: targetUserId })
  const updated = await findUserProfileById(targetUserId, req.session.userId)
  res.json({ user: updated })
})

module.exports = router
