# -*- coding: utf-8 -*-
import base64
import logging

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

_logger = logging.getLogger(__name__)


class OdspPreApprovedWizard(models.TransientModel):
    _name = 'fusion_claims.odsp.pre.approved.wizard'
    _description = 'ODSP Pre-Approved - Upload Approval Form'

    sale_order_id = fields.Many2one(
        'sale.order', string='Sale Order', readonly=True, required=True,
    )
    approval_form = fields.Binary(
        string='ODSP Approval Form (PDF)',
        required=True,
        help='Upload the PDF received from ODSP containing the approval letter and SA Mobility form.',
    )
    approval_form_filename = fields.Char(string='Filename')

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        active_id = self.env.context.get('active_id')
        if active_id:
            res['sale_order_id'] = active_id
        return res

    def action_confirm(self):
        self.ensure_one()
        if not self.approval_form:
            raise UserError("Please upload the ODSP approval form PDF.")

        order = self.sale_order_id
        filename = self.approval_form_filename or f'ODSP_Approval_{order.name}.pdf'

        if order.x_fc_odsp_division == 'sa_mobility':
            order.write({
                'x_fc_sa_approval_form': self.approval_form,
                'x_fc_sa_approval_form_filename': filename,
            })
        elif order.x_fc_odsp_division == 'standard':
            order.write({
                'x_fc_odsp_approval_document': self.approval_form,
                'x_fc_odsp_approval_document_filename': filename,
            })

        att = self.env['ir.attachment'].create({
            'name': filename,
            'type': 'binary',
            'datas': self.approval_form,
            'res_model': 'sale.order',
            'res_id': order.id,
            'mimetype': 'application/pdf',
        })

        from markupsafe import Markup
        order.message_post(
            body=Markup("ODSP approval document uploaded: <strong>%s</strong>") % filename,
            message_type='comment',
            attachment_ids=[att.id],
        )

        order._odsp_advance_status('pre_approved', "ODSP pre-approval received.")

        return {'type': 'ir.actions.act_window_close'}
