from odoo import fields,models,api,_
from odoo.exceptions import UserError
class LoanCredit(models.Model):
    _name = "loan.credit"
    _description = "Loan Credit Profile"

    partner_id = fields.Many2one(
        'res.partner',
        string='Customer Name',
    )
    loan_id = fields.Many2one(
        'loan.management',
        string='Loan Data',
    )
    credit_date = fields.Date("Credit Date")
    credit_type = fields.Selection([
        ('interest','Interest'),
        ('capital','Capital'),
        ('mix','Interest + Capital'),
    ],string='Credit Type')
    credit_amount = fields.Float("Credit Amount")
    interest_amount = fields.Float("Interest Amount")

    @api.model
    def create(self, vals_list):
        for vals in vals_list:
            loan = self.env['loan.management'].browse(vals.get('loan_id'))

            credit_amount = vals.get('credit_amount', 0.0)
            if loan and credit_amount > loan.remaining_capital:
                raise UserError(
                    _("Credit amount cannot be greater than remaining capital.")
                )

        return super().create(vals_list)


    def write(self, vals):
        for rec in self:
            credit_amount = vals.get('credit_amount', rec.credit_amount)
            loan = rec.loan_id

            if loan and credit_amount > loan.remaining_capital:
                raise UserError(
                    _("Credit amount cannot be greater than remaining capital.")
                )

        return super().write(vals)