'use strict'

const { query, queryOne } = require('../database/postgres')

class Broadcast {
  static async send(tenantId, fromAccount, content) {
    return queryOne(
      `INSERT INTO broadcasts (tenant_id, from_account, content)
       VALUES ($1, $2, $3)
       RETURNING id, from_account, content, created_at`,
      [tenantId, fromAccount, content]
    )
  }

  static async list(tenantId, limit = 50) {
    return query(
      `SELECT b.id, b.from_account, b.content, b.created_at,
              a.name AS sender_name, a.avatar_url AS sender_avatar
       FROM broadcasts b
       LEFT JOIN accounts a ON a.id = b.from_account
       WHERE b.tenant_id = $1
       ORDER BY b.created_at DESC
       LIMIT $2`,
      [tenantId, limit]
    )
  }

  /**
   * Quantidade de broadcasts não vistos pelo colaborador
   */
  static async unreadCount(tenantId, accountId) {
    const row = await queryOne(
      `SELECT COUNT(*)::int AS count
       FROM broadcasts b
       LEFT JOIN broadcast_last_seen bls
         ON bls.tenant_id = $1 AND bls.account_id = $2
       WHERE b.tenant_id = $1
         AND b.from_account != $2
         AND (bls.last_seen_at IS NULL OR b.created_at > bls.last_seen_at)`,
      [tenantId, accountId]
    )
    return row?.count ?? 0
  }

  /**
   * Marcar broadcasts como vistos (upsert last_seen_at)
   */
  static async markSeen(tenantId, accountId) {
    await queryOne(
      `INSERT INTO broadcast_last_seen (account_id, tenant_id, last_seen_at)
       VALUES ($1, $2, NOW())
       ON CONFLICT (account_id, tenant_id)
       DO UPDATE SET last_seen_at = NOW()`,
      [accountId, tenantId]
    )
  }
}

module.exports = Broadcast
