import json
import logging

import requests
from django.conf import settings

from app.api import api
from app.api.api_accessor import APIAccessor
from app.util import datetime_util, util

log = logging.getLogger(__name__)


class LotusPayAccessor(APIAccessor):
    CREATE_SOURCE_URL = f"{settings.LOTUS_PAY_BASE_URL}/v1/sources"

    @classmethod
    def create_mandate(cls, date_first_collection, date_final_collection, amount_maximum, ifsc_code,
                       debtor_account_name, debtor_account_number, debtor_account_type, frequency, redirect_url,
                       transaction_id):
        """
            ADHO/MNTH/QURT/MIAN/YEAR/INDA/WEEK

            [21/Aug/2023 11:50:41] DEBUG [de2fc90f867f4971ab8b82366b3a5a50] [app.api.api_accessor:15] API response: 201 b'{"id":"SC0060I8XDYHHN","object":"source","created":1692618641,"livemode":false,"metadata":{},"client_secret":"src_client_secret_MousbERO63stOIojMKzP3vWt","date_submitted":null,"date_withdrawn":null,"flow":null,"nach_debit":{"amount_collection":null,"amount_maximum":86000,"category_code":"L001","category_description":"Loan Instalment Payment","creditor_agent_code":"ICIC","creditor_agent_mmbid":"ICIC0TREA00","creditor_agent_name":"ICICI BANK LTD","creditor_name":"K M GLOBAL CREDIT PVT LTD","creditor_utility_code":"NACH00000000021321","date_final_collection":null,"date_first_collection":"2023-09-05","debtor_account_name":"SCARLETT BARKER","debtor_account_number":"******3456","debtor_account_type":"savings","debtor_agent_code":"SBIN","debtor_agent_name":"State Bank of India","debtor_agent_mmbid":"SBIN0004245","debtor_email":null,"debtor_mobile":null,"debtor_pan":null,"debtor_phone":null,"frequency":"MNTH","instrument":"DEBIT","occurrence_sequence_type":"RCUR","reference1":null,"reference2":null,"variant":"emandate_api"},"origin":"API","redirect":{"return_url":"https://deployment.d1g73iuyh860r3.amplifyapp.com/customers/mandate/redirect/url/","auth_mode":null,"response":{},"url":"https://test.lotuspay.com/pay/AL0023HJLW7FQ6?client_secret=src_client_secret_MousbERO63stOIojMKzP3vWt","auth_attempts":null,"response_code":null,"short_url":null},"sms":null,"type":"nach_debit","status":"pending","agent":null,"bank_account":null,"customer":null,"mandate":null,"nach_profile":"NP0011PZ4B8EAR"}'
            [21/Aug/2023 11:50:41] INFO [de2fc90f867f4971ab8b82366b3a5a50] [backend.middleware:61] [RESPONSE] [PATH] /v1/mandate/setup/ [TIME] 272 ms [STATUS_CODE] 200 [CONTENT] {'status-code': 1, 'status-message': 'Mandate link generated', 'data': {'mandate_registration_url': 'https://test.lotuspay.com/pay/AL0023HJLW7FQ6?client_secret=src_client_secret_MousbERO63stOIojMKzP3vWt'}}
            [21/Aug/2023 11:50:41] "POST /v1/mandate/setup/ HTTP/1.1" 200 199

            Success response:
            https://deployment.d1g73iuyh860r3.amplifyapp.com/customers/mandate/redirect/url?client_secret=src_client_secret_715tE8WDPRvEOmdbHBoVeuyz&livemode=false&source_id=SC0035QUPQCXBK
            https://deployment.d1g73iuyh860r3.amplifyapp.com/customers/mandate/redirect/url?client_secret=src_client_secret_UiowVkktOzcbYmoKokd1lNQW&source_id=SC0013UGD9LY4V&livemode=false
        """
        data = {
            "type": "nach_debit",
            "redirect": {
                "return_url": redirect_url
            },
            "nach_debit": {
                "date_first_collection": datetime_util.get_date_string_yyyy_mm_dd(date_first_collection),
                "date_final_collection": datetime_util.get_date_string_yyyy_mm_dd(date_final_collection),
                "amount_maximum": amount_maximum,
                "debtor_agent_mmbid": ifsc_code,
                "debtor_account_name": debtor_account_name,
                "debtor_account_number": debtor_account_number,
                "debtor_account_type": debtor_account_type,
                "frequency": frequency,
                "creditor_utility_code": settings.LOTUS_PAY_UTILITY_CODE,
                "creditor_agent_code": settings.LOTUS_PAY_AGENT_CODE
            },
            "metadata": {
                "transaction_id": transaction_id,
                "source": "emi-checkout"
            }
        }

        headers = {
            "Authorization": f"Bearer {settings.LOTUS_PAY_SECRET_KEY}",
            "Content-Type": "application/json"
        }
        status, response = cls.request(
            requests.request, method="post", data=json.dumps(data), url=cls.CREATE_SOURCE_URL, headers=headers)
        if util.is_status_failed(status):
            return status, None

        if not ('redirect' in response and 'url' in response['redirect']):
            log.error('Mandate setup failed')
            return api.MANDATE_SETUP_REQUEST_FAILED, None

        result = {
            "url": response['redirect']['url']
        }

        return api.SUCCESS, result
