'use server'

import { z } from 'zod'
import { prisma } from '@/lib/prisma'
import { getSession } from '@/lib/auth'

const subscribeSchema = z.object({
  endpoint: z.string().url(),
  keys: z.object({
    p256dh: z.string().min(1),
    auth: z.string().min(1),
  }),
  userAgent: z.string().optional(),
})

export type SubscribeToPushInput = z.infer<typeof subscribeSchema>

export async function subscribeToPushAction(input: SubscribeToPushInput): Promise<void> {
  const session = await getSession()
  if (!session.userId) return
  if (session.isDemo) return

  const parsed = subscribeSchema.safeParse(input)
  if (!parsed.success) return

  const { endpoint, keys, userAgent } = parsed.data
  await prisma.pushSubscription.upsert({
    where: { endpoint },
    create: {
      user_id: session.userId,
      endpoint,
      p256dh: keys.p256dh,
      auth: keys.auth,
      user_agent: userAgent ?? null,
    },
    update: {
      user_id: session.userId,
      p256dh: keys.p256dh,
      auth: keys.auth,
      last_used_at: new Date(),
    },
  })
}

export async function unsubscribeFromPushAction(args: { endpoint: string }): Promise<void> {
  const session = await getSession()
  if (!session.userId) return

  await prisma.pushSubscription.deleteMany({
    where: { endpoint: args.endpoint, user_id: session.userId },
  })
}
