from odoo import http, _
from odoo.http import request
from odoo.addons.web.controllers.main import Home
import random
import json

class AuthSignInHome(Home):
    @http.route('/generate_otp', type='http', auth="public", website=True)
    def generate_otp(self, **kw):
        msg = _("No user found with the provided mobile phone number.")
        data = {
            'status': False,
            'msg': msg
        }    
        if not kw.get('otp_mobile_phone'):
            msg = _("Please provide a mobile phone number.")
            data['msg'] = msg
        else:
            # Get the target boolean field name for the account_type
            target_field = request.env['res.partner'].sudo().get_partner_target_account_type(kw.get('account_type'))

            user = request.env['res.users'].sudo().search([
                    ('login', '=', kw.get('otp_mobile_phone')), 
                    # ('partner_id.account_type', '=', kw.get('account_type'))
                    ('partner_id.%s' % target_field, '=', True)
                ], limit=1)
            if user:
                msg = _("OTP has been sent to your mobile phone number.")
                data['status'] = True
                data['msg'] = msg
                user.generate_otp()
       
        return json.dumps(data)

    @http.route('/validate_otp/login', type='http', auth="public", website=True)
    def validate_otp(self, **kw):
        user = request.env['res.users'].sudo().search([('login', '=', kw.get('otp_mobile_phone'))], limit=1)
        otp = kw.get('otp')

        if user and user.sudo().validate_otp(otp):
            # Activate the user
            user.sudo().write({'active': True})

            # Commit before authentication
            request.env.cr.commit()

            # Authenticate the user properly
            request.session.authenticate(request.db, user.login, otp)

            # Response with success and redirect URL
            data = {
                'status': True,
                'url': '/web',
                'partner_id': user.partner_id.id,
            }
        else:
            # OTP validation failed
            msg = _("Invalid OTP. Please try again.")
            data = {
                'status': False,
                'msg': msg,
            }

        return request.make_response(json.dumps(data), headers={'Content-Type': 'application/json'})