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


class BrosseBankTransactionsStatusCode(models.Model):
    _name = 'brosse.bank.transactions.status.code'
    _description = 'Bank Transactions Status Code'

    name = fields.Char(string='Name')
    code = fields.Integer(string='Code')


class BrosseBankTransactionsSubtypeCode(models.Model):
    _name = 'brosse.bank.transactions.subtype.code'
    _description = 'Bank Transactions Subtype Code'

    name = fields.Char(string='Name')
    code = fields.Integer(string='Code')


class BrosseBankTransactions(models.Model):
    _name = 'brosse.bank.transactions'
    _description = 'Bank Transactions'
    _rec_name = 'document_number'

    movement_id = fields.Char(string='Movement ID')
    external_payment_id = fields.Char(string='External Payment ID')
    debit_credit = fields.Boolean(string='Debit/Credit', help="False = Debit, True = Credit")
    value_date = fields.Date(string='Value Date')
    description = fields.Char(string="Description")
    amount = fields.Monetary(string="Amount", currency_field='currency_id')
    currency_id = fields.Many2one('res.currency', string='Currency')
    account_number = fields.Char(string='Account Number')
    account_name = fields.Char(string='Account Name')
    comment = fields.Text(string="Comment")
    document_date = fields.Date(string='Document Date')
    document_number = fields.Char(string='Document Number')
    partner_name = fields.Char(string="Partner Name")
    partner_tax_code = fields.Char(string='Partner Tax Code')
    taxpayer_code = fields.Char(string='Taxpayer Code')
    taxpayer_name = fields.Char(string="Taxpayer Name")
    operation_code = fields.Char(string='Operation Code')
    exchange_rate = fields.Float(string="Exchange Rate")
    exchange_rate_text = fields.Char(string='Exchange Rate (Text)')
    partner_personal_number = fields.Char(string='Partner Personal Number')
    partner_document_type = fields.Char(string='Partner Document Type')
    partner_document_number = fields.Char(string='Partner Document Number')
    parent_external_payment_id = fields.Char(string='Parent External Payment ID')
    status_code_id = fields.Many2one('brosse.bank.transactions.status.code', string='Status Code')
    transaction_type_id = fields.Many2one('brosse.bank.transactions.subtype.code', string='Transaction Type')

    payments_ids = fields.One2many(comodel_name="hms.payments", inverse_name="transaction_id", string="HMS Payments")

    unassigned_amount = fields.Monetary(string="Unassigned Amount", currency_field='currency_id', compute="_compute_unassigned_amount")

    bank_account_id = fields.Many2one('brosse.bank.account', string="Bank Account")

    category_id = fields.Many2one('hms.payment.categories', string='Category')
    manually_assigned = fields.Boolean(string="Manually Assigned", default=False)

    @api.depends('payments_ids')
    def _compute_unassigned_amount(self):
        for rec in self:
            if rec.payments_ids:
                gel_currency_id = self.env['res.currency'].search([('name', '=', 'GEL')])
                payments = 0
                unassigned_amount = 0
                for payment in rec.payments_ids:
                    if rec.currency_id.id == gel_currency_id.id:
                        if payment.currency_id.id == rec.currency_id.id:
                            payments += payment.amount
                        else:
                            payments += payment.amount * payment.currency_id.rate_ids.sorted('id', reverse=True)[0].rate
                    else:
                        if payment.currency_id.id == rec.currency_id.id:
                            payments += payment.amount
                        else:
                            payments += payment.amount * payment.currency_id.rate_ids.sorted('id', reverse=True)[0].rate / rec.currency_id.rate_ids.sorted('id', reverse=True)[0].rate

                unassigned_amount = rec.amount - payments
            else:
                unassigned_amount = rec.amount
            rec.unassigned_amount = unassigned_amount

    @api.onchange('category_id')
    def onchange_category_id(self):
        if self.category_id:
            self.write({'manually_assigned': True})

    @api.depends('document_date', 'amount')
    def _compute_display_name(self):
        for rec in self:
            rec.display_name = f"{rec.document_date} / {rec.amount} {rec.currency_id.symbol}" if rec.document_date and rec.amount else ""
    
    def action_process_selected_records(self):
        booking_id = self.env.context.get('booking_id')
        booking = self.env['hms.bookings'].browse(booking_id)

        for rec in self:
            if booking.payment_ids:
                to_pay = booking.total_amount - sum(booking.payment_ids.mapped('amount'))
            else:
                to_pay = booking.total_amount
                
            self.env['hms.payments'].create({
                'transaction_id': rec.id,
                'booking_id': booking.id,
                'currency_id': rec.currency_id.id,
                'amount': rec.amount,
                'exchange_rate': rec.exchange_rate,
            })
