import {RegisterPushTokenSchema} from '@crumbs/core/schemas'
import {and, eq} from 'drizzle-orm'
import {Hono} from 'hono'
import {z} from 'zod'

import {type GuardedVars} from '../auth/middleware'
import {db, schema} from '../db/client'
import {validate} from '../lib/validate'

const pushTokens = new Hono<{Variables: GuardedVars}>()
  .post('/', validate('json', RegisterPushTokenSchema), async (c) => {
    const user = c.get('user')
    const {token, platform, timezone} = c.req.valid('json')
    await db
      .insert(schema.pushTokens)
      .values({
        userId: user.id,
        token,
        platform,
        timezone: timezone ?? null,
      })
      .onConflictDoUpdate({
        target: schema.pushTokens.token,
        set: {
          userId: user.id,
          timezone: timezone ?? null,
          updatedAt: new Date(),
        },
      })
    return c.json({ok: true})
  })
  .delete(
    '/',
    validate('json', z.object({token: z.string().min(1).max(200)})),
    async (c) => {
      const user = c.get('user')
      const {token} = c.req.valid('json')
      await db
        .delete(schema.pushTokens)
        .where(
          and(
            eq(schema.pushTokens.token, token),
            eq(schema.pushTokens.userId, user.id),
          ),
        )
      return c.json({ok: true})
    },
  )

export default pushTokens
