# -*- coding: utf-8 -*-
# Copyright 2024-2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

"""
Web Push Subscription model for storing browser push notification subscriptions.
"""

from odoo import models, fields, api
import logging

_logger = logging.getLogger(__name__)


class FusionPushSubscription(models.Model):
    _name = 'fusion.push.subscription'
    _description = 'Web Push Subscription'
    _order = 'create_date desc'

    user_id = fields.Many2one(
        'res.users',
        string='User',
        required=True,
        ondelete='cascade',
        index=True,
    )
    endpoint = fields.Text(
        string='Endpoint URL',
        required=True,
    )
    p256dh_key = fields.Text(
        string='P256DH Key',
        required=True,
    )
    auth_key = fields.Text(
        string='Auth Key',
        required=True,
    )
    browser_info = fields.Char(
        string='Browser Info',
        help='User agent or browser identification',
    )
    active = fields.Boolean(
        default=True,
    )

    _constraints = [
        models.Constraint(
            'unique(endpoint)',
            'This push subscription endpoint already exists.',
        ),
    ]

    @api.model
    def register_subscription(self, user_id, endpoint, p256dh_key, auth_key, browser_info=None):
        """Register or update a push subscription."""
        existing = self.sudo().search([('endpoint', '=', endpoint)], limit=1)
        if existing:
            existing.write({
                'user_id': user_id,
                'p256dh_key': p256dh_key,
                'auth_key': auth_key,
                'browser_info': browser_info or existing.browser_info,
                'active': True,
            })
            return existing
        return self.sudo().create({
            'user_id': user_id,
            'endpoint': endpoint,
            'p256dh_key': p256dh_key,
            'auth_key': auth_key,
            'browser_info': browser_info,
        })
