# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
import logging

_logger = logging.getLogger(__name__)


class AuthorizerComment(models.Model):
    _name = 'fusion.authorizer.comment'
    _description = 'Authorizer/Sales Rep Comment'
    _order = 'create_date desc'
    _rec_name = 'display_name'

    sale_order_id = fields.Many2one(
        'sale.order',
        string='Sale Order',
        required=True,
        ondelete='cascade',
        index=True,
    )
    
    assessment_id = fields.Many2one(
        'fusion.assessment',
        string='Assessment',
        ondelete='cascade',
        index=True,
    )
    
    author_id = fields.Many2one(
        'res.partner',
        string='Author',
        required=True,
        default=lambda self: self.env.user.partner_id,
        index=True,
    )
    
    author_user_id = fields.Many2one(
        'res.users',
        string='Author User',
        default=lambda self: self.env.user,
        index=True,
    )
    
    comment = fields.Text(
        string='Comment',
        required=True,
    )
    
    comment_type = fields.Selection([
        ('general', 'General Comment'),
        ('question', 'Question'),
        ('update', 'Status Update'),
        ('internal', 'Internal Note'),
    ], string='Type', default='general')
    
    is_internal = fields.Boolean(
        string='Internal Only',
        default=False,
        help='If checked, this comment will not be visible to portal users',
    )
    
    display_name = fields.Char(
        string='Display Name',
        compute='_compute_display_name',
        store=True,
    )

    @api.depends('author_id', 'create_date')
    def _compute_display_name(self):
        for comment in self:
            if comment.author_id and comment.create_date:
                comment.display_name = f"{comment.author_id.name} - {comment.create_date.strftime('%Y-%m-%d %H:%M')}"
            else:
                comment.display_name = _('New Comment')

    @api.model_create_multi
    def create(self, vals_list):
        """Override create to set author from current user if not provided"""
        for vals in vals_list:
            if not vals.get('author_id'):
                vals['author_id'] = self.env.user.partner_id.id
            if not vals.get('author_user_id'):
                vals['author_user_id'] = self.env.user.id
        return super().create(vals_list)
