# Fusion Accounting - Fiscal Year Management
# Defines company-specific fiscal year periods with overlap validation

from odoo import api, fields, models, _
from odoo.exceptions import ValidationError


class FusionFiscalYear(models.Model):
    """Represents a fiscal year period for a company. Enforces
    non-overlapping date ranges and prevents child-company assignments."""

    _name = 'account.fiscal.year'
    _description = 'Fiscal Year'

    name = fields.Char(
        string='Name',
        required=True,
    )
    date_from = fields.Date(
        string='Start Date',
        required=True,
        help='First day of the fiscal year (inclusive).',
    )
    date_to = fields.Date(
        string='End Date',
        required=True,
        help='Last day of the fiscal year (inclusive).',
    )
    company_id = fields.Many2one(
        comodel_name='res.company',
        string='Company',
        required=True,
        default=lambda self: self.env.company,
    )

    @api.constrains('date_from', 'date_to', 'company_id')
    def _validate_fiscal_year_dates(self):
        """Ensure fiscal years do not overlap for the same company and
        that the date range is logically ordered. Fiscal years on child
        companies are disallowed.

        Overlap scenarios checked:
            s1  s2  e1  e2   ->  new starts inside existing
            s2  s1  e2  e1   ->  existing starts inside new
            s1  s2  e2  e1   ->  existing fully inside new
        """
        for fiscal_year in self:
            if fiscal_year.date_to < fiscal_year.date_from:
                raise ValidationError(
                    _('The end date cannot be earlier than the start date.')
                )

            if fiscal_year.company_id.parent_id:
                raise ValidationError(
                    _('Fiscal years cannot be defined on subsidiary companies.')
                )

            overlap_domain = [
                ('id', '!=', fiscal_year.id),
                ('company_id', '=', fiscal_year.company_id.id),
                '|', '|',
                '&', ('date_from', '<=', fiscal_year.date_from), ('date_to', '>=', fiscal_year.date_from),
                '&', ('date_from', '<=', fiscal_year.date_to), ('date_to', '>=', fiscal_year.date_to),
                '&', ('date_from', '<=', fiscal_year.date_from), ('date_to', '>=', fiscal_year.date_to),
            ]

            if self.search_count(overlap_domain) > 0:
                raise ValidationError(
                    _('Fiscal years for the same company must not overlap. '
                      'Please adjust the start or end dates.')
                )
