import admin from 'firebase-admin'
import { getDb } from '../db/client.js'
import { UserType } from '../constants.js'

const sql = getDb()

export const registerDeviceToken = async (userType, userId, fcmToken) => {
  const table = userType === UserType.CUSTOMER ? 'customers' : 'mitras'
  await sql`
    UPDATE ${sql(table)}
    SET fcm_token = ${fcmToken}
    WHERE id = ${userId}
  `
}

export const sendPushNotification = async (recipientType, recipientId, { title, body, data = {} }) => {
  const table = recipientType === UserType.CUSTOMER ? 'customers' : 'mitras'
  const [user] = await sql`
    SELECT fcm_token FROM ${sql(table)} WHERE id = ${recipientId}
  `

  if (!user?.fcm_token) return false

  try {
    await admin.messaging().send({
      token: user.fcm_token,
      notification: { title, body },
      data: {
        ...Object.fromEntries(
          Object.entries(data).map(([k, v]) => [k, String(v)])
        ),
        click_action: 'FLUTTER_NOTIFICATION_CLICK',
      },
      android: {
        priority: 'high',
        notification: { channelId: 'chat_messages' },
      },
      apns: {
        payload: {
          aps: { sound: 'default', badge: 1 },
        },
      },
    })
    return true
  } catch (err) {
    console.error(`[FCM] Failed to send to ${recipientType}:${recipientId}:`, err.message)
    // Clear invalid token
    if (err.code === 'messaging/registration-token-not-registered') {
      await sql`UPDATE ${sql(table)} SET fcm_token = NULL WHERE id = ${recipientId}`
    }
    return false
  }
}
