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

from odoo import models, fields, api


class ResPartner(models.Model):
    _inherit = 'res.partner'

    brand_ids = fields.One2many(
        'product.brand', 'partner_id', string='Brands')
    brand_count = fields.Integer(
        string='Brands', compute='_compute_brand_count')

    def _compute_brand_count(self):
        for partner in self:
            partner.brand_count = len(partner.brand_ids)

    def action_view_brands(self):
        self.ensure_one()
        brands = self.brand_ids
        if len(brands) == 1:
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'product.brand',
                'res_id': brands.id,
                'view_mode': 'form',
            }
        return {
            'type': 'ir.actions.act_window',
            'name': f'Brands: {self.name}',
            'res_model': 'product.brand',
            'view_mode': 'list,form',
            'domain': [('partner_id', '=', self.id)],
            'context': {'default_partner_id': self.id},
        }

    def action_create_brand(self):
        self.ensure_one()
        existing = self.env['product.brand'].search(
            [('partner_id', '=', self.id)], limit=1)
        if existing:
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'product.brand',
                'res_id': existing.id,
                'view_mode': 'form',
            }
        brand = self.env['product.brand'].create({
            'name': self.name,
            'partner_id': self.id,
            'logo': self.image_128 or False,
        })
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'product.brand',
            'res_id': brand.id,
            'view_mode': 'form',
        }
