# -*- coding: utf-8 -*-
from datetime import date

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


class FamilyLawChild(models.Model):
    _name = "familylaw.child"
    _description = "Minor Child"
    _order = "name"

    case_id = fields.Many2one(
        "familylaw.case",
        required=True,
        ondelete="cascade",
        index=True,
    )
    name = fields.Char(required=True)
    date_of_birth = fields.Date(string="Date of Birth")
    age = fields.Integer(
        compute="_compute_age",
        string="Age",
    )
    notes = fields.Text()

    @api.depends("date_of_birth")
    def _compute_age(self):
        today = date.today()
        for child in self:
            if not child.date_of_birth:
                child.age = 0
                continue
            dob = child.date_of_birth
            child.age = (
                today.year - dob.year
                - ((today.month, today.day) < (dob.month, dob.day))
            )

    @api.constrains("date_of_birth")
    def _check_date_of_birth(self):
        today = date.today()
        for child in self:
            if not child.date_of_birth:
                continue
            dob = child.date_of_birth
            if dob > today:
                raise ValidationError(
                    "Date of birth cannot be in the future."
                )
            age = (
                today.year - dob.year
                - ((today.month, today.day) < (dob.month, dob.day))
            )
            if age > 25:
                raise ValidationError(
                    f"Date of birth implies the child is {age} years old. "
                    "Verify the date — this field is for minor children in the matter."
                )
