# -*- coding: utf-8 -*-
# Copyright 2024-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'

    # ==========================================================================
    # CONTACT TYPE
    # ==========================================================================
    x_fc_contact_type = fields.Selection(
        selection=[
            ('adp_customer', 'ADP Customer'),
            ('adp_odsp_customer', 'ADP-ODSP Customer'),
            ('odsp_customer', 'ODSP Customer'),
            ('mod_customer', 'MOD Customer'),
            ('private_customer', 'Private Customer'),
            ('wsib_customer', 'WSIB Customer'),
            ('acsd_customer', 'ACSD Customer'),
            ('private_insurance', 'Private Insurance'),
            ('adp_agent', 'ADP Agent'),
            ('odsp_agent', 'ODSP Agent'),
            ('muscular_dystrophy', 'Muscular Dystrophy'),
            ('occupational_therapist', 'Occupational Therapist'),
            ('physiotherapist', 'Physiotherapist'),
            ('vendor', 'Vendor'),
            ('funding_agency', 'Funding Agency'),
            ('government_agency', 'Government Agency'),
            ('company_contact', 'Company Contact'),
            ('long_term_care_home', 'Long Term Care Home'),
            ('retirement_home', 'Retirement Home'),
            ('odsp_office', 'ODSP Office'),
            ('other', 'Other'),
        ],
        string='Contact Type',
        tracking=True,
        index=True,
    )

    # ==========================================================================
    # ODSP FIELDS
    # ==========================================================================
    x_fc_odsp_member_id = fields.Char(
        string='ODSP Member ID',
        size=9,
        tracking=True,
        help='9-digit Ontario Disability Support Program Member ID',
    )
    x_fc_case_worker_id = fields.Many2one(
        'res.partner',
        string='ODSP Case Worker',
        tracking=True,
        help='ODSP Case Worker assigned to this client',
    )
    x_fc_date_of_birth = fields.Date(
        string='Date of Birth',
        tracking=True,
    )
    x_fc_healthcard_number = fields.Char(
        string='Healthcard Number',
        tracking=True,
    )
    x_fc_is_odsp_office = fields.Boolean(
        compute='_compute_is_odsp_office',
        string='Is ODSP Office',
        store=True,
    )

    # ==========================================================================
    # AUTHORIZER FIELDS
    # ==========================================================================
    x_fc_authorizer_number = fields.Char(
        string='ADP Authorizer Number',
        tracking=True,
        index=True,
        help='ADP Registration Number for this authorizer (e.g. OT). '
             'Used to auto-link authorizers when processing ADP XML files.',
    )
    x_fc_adp_application_count = fields.Integer(
        string='ADP Applications',
        compute='_compute_adp_application_count',
    )

    @api.depends('x_fc_contact_type')
    def _compute_is_odsp_office(self):
        for partner in self:
            partner.x_fc_is_odsp_office = partner.x_fc_contact_type == 'odsp_office'

    def _compute_adp_application_count(self):
        AppData = self.env['fusion.adp.application.data']
        for partner in self:
            domain = self._get_authorizer_application_domain(partner)
            partner.x_fc_adp_application_count = AppData.search_count(domain) if domain else 0

    def _get_authorizer_application_domain(self, partner):
        """Build domain to find applications linked to this authorizer."""
        conditions = []
        if partner.x_fc_authorizer_number:
            conditions.append(('authorizer_adp_number', '=', partner.x_fc_authorizer_number))
        name = (partner.name or '').strip()
        if name:
            parts = name.replace(',', ' ').split()
            if len(parts) >= 2:
                conditions.append(
                    '&',
                )
                conditions.append(('authorizer_last_name', 'ilike', parts[0]))
                conditions.append(('authorizer_first_name', 'ilike', parts[-1]))
        if not conditions:
            return []
        if len(conditions) > 3:
            return ['|'] + conditions
        return conditions

    def action_view_adp_applications(self):
        self.ensure_one()
        domain = self._get_authorizer_application_domain(self)
        return {
            'name': 'ADP Applications',
            'type': 'ir.actions.act_window',
            'res_model': 'fusion.adp.application.data',
            'view_mode': 'list,form',
            'domain': domain,
            'context': {'default_authorizer_adp_number': self.x_fc_authorizer_number or ''},
        }
