"""
This script clears a merchant cache when:
# An item was edited, added, removed
# Once an edit is made to a merchant order type
# A merchant is deactivated or reactivated
"""

import requests
import re
from helpers import response_data
from helpers.environment import get_environment

def main():
    environment_url = get_environment()
    merchant_id = get_merchant_id()
    
    print(f'You are clearing the cache for merchant: {merchant_id} at {environment_url}')
    answer = input('continue? (Y/n): ').lower().strip()
    
    if answer == 'y' or answer == '':
        clear_cache(environment_url, merchant_id)
    else:
        print('exiting...')


def get_merchant_id():
    merchant_id = input('Merchant ID: ')
    valid_id = re.match("^\d{4,8}$", merchant_id)
    while not valid_id:
        print("Please enter a valid merchant ID. ")
        merchant_id = input('Merchant ID: ')
        valid_id = re.match("^\d{4,8}$", merchant_id)
    return merchant_id


def clear_cache(environment, merchant_id):
    url = f'{environment}/api/merchant/admin/cache/{merchant_id}'
    response = requests.delete(url=url)
    response_data.validate_response(response)


if __name__ == "__main__":
    main()
