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

from odoo import models, fields, api, _


class PayrollWorkLocation(models.Model):
    """
    Work Location
    Represents a physical work location where employees work.
    """
    _name = 'payroll.work.location'
    _description = 'Work Location'
    _order = 'is_primary desc, name'

    name = fields.Char(
        string='Location Name',
        help='Name or identifier for this work location',
    )
    company_id = fields.Many2one(
        'res.company',
        string='Company',
        required=True,
        default=lambda self: self.env.company,
        ondelete='cascade',
    )
    street = fields.Char(
        string='Street Address',
    )
    street2 = fields.Char(
        string='Street Address 2',
    )
    city = fields.Char(
        string='City',
    )
    state_id = fields.Many2one(
        'res.country.state',
        string='Province',
        domain="[('country_id', '=?', country_id)]",
    )
    zip = fields.Char(
        string='Postal Code',
    )
    country_id = fields.Many2one(
        'res.country',
        string='Country',
        default=lambda self: self.env.ref('base.ca', raise_if_not_found=False),
    )
    is_primary = fields.Boolean(
        string='Primary Location',
        default=False,
        help='Mark this as the primary work location',
    )
    status = fields.Selection([
        ('active', 'Active'),
        ('inactive', 'Inactive'),
    ], string='Status', default='active', required=True)
    
    employee_ids = fields.Many2many(
        'hr.employee',
        'payroll_work_location_employee_rel',
        'location_id',
        'employee_id',
        string='Employees',
        help='Employees assigned to this work location',
    )
    employee_count = fields.Integer(
        string='Employees Assigned',
        compute='_compute_employee_count',
        store=True,
    )

    @api.depends('employee_ids')
    def _compute_employee_count(self):
        """Compute number of employees assigned to this location."""
        for location in self:
            location.employee_count = len(location.employee_ids)

    @api.constrains('is_primary')
    def _check_primary_location(self):
        """Ensure only one primary location per company."""
        for location in self:
            if location.is_primary:
                other_primary = self.search([
                    ('company_id', '=', location.company_id.id),
                    ('is_primary', '=', True),
                    ('id', '!=', location.id),
                ])
                if other_primary:
                    raise UserError(_('Only one primary location is allowed per company.'))

    def name_get(self):
        """Return display name with address."""
        result = []
        for location in self:
            name = location.name or _('Unnamed Location')
            if location.city:
                name = f"{name}, {location.city}"
            if location.state_id:
                name = f"{name}, {location.state_id.code}"
            if location.is_primary:
                name = f"{name} ({_('PRIMARY')})"
            result.append((location.id, name))
        return result
