import {BlockUserSchema} from '@crumbs/core/schemas'
import {Hono} from 'hono'
import {HTTPException} from 'hono/http-exception'

import {type GuardedVars} from '../auth/middleware'
import {uuidParams, validate} from '../lib/validate'
import {blockUser, unblockUser} from '../services/blocks'
import {requireUserExists} from '../services/users'

// blocking severs the relationship and hides each user from the other; the
// heavy lifting (friendship removal, invite cleanup) lives in the service
const blocks = new Hono<{Variables: GuardedVars}>()
  .post('/', validate('json', BlockUserSchema), async (c) => {
    const me = c.get('user')
    const {userId} = c.req.valid('json')
    if (userId === me.id)
      throw new HTTPException(400, {message: 'cannot_block_self'})
    await requireUserExists(userId)
    await blockUser(me.id, userId)
    return c.json({ok: true})
  })
  .delete('/:userId', uuidParams('userId'), async (c) => {
    const me = c.get('user')
    const {userId} = c.req.valid('param')
    await unblockUser(me.id, userId)
    return c.json({ok: true})
  })

export default blocks
