import boto3
import json

def lambda_handler(event, context):
    # Define Domains to be changed
    #domains = ["billing.bwnetwork.us", "bitwarden.bwnetwork.us", "cloud.bwnetwork.us", "git.bwnetwork.us"]
    # Extract the public IP address from the event
    public_ip = event.get('public_ip')
    domain = event.get('domain')
    zoneId=event.get('zoneId')
    ttl=event.get('ttl')

    if not public_ip:
        return {'error': 'Public IP address not provided.'}
    if not domain:
        return {'error': 'Domain not provided.'}
    if not zoneId:
        return {'error': 'Hosted Zone ID not provided.'}
    if not ttl:
        return {'error': 'TTL not provided.'}

    # Define the changes to be made to the DNS record
    changes = {
        'Comment': 'Update record to reflect new IP address',
        'Changes': [{
            'Action': 'UPSERT',
            'ResourceRecordSet': {
                'Name': domain,
                'Type': 'A',
                'TTL': ttl,
                'ResourceRecords': [{'Value': public_ip}]
            }
        }]
    }
        # Update the Route 53 record
    client = boto3.client('route53')
    response = client.change_resource_record_sets(
        HostedZoneId=zoneId,
        ChangeBatch=changes
    )

        # Create a custom response
    custom_response = {
        "Status": response['ChangeInfo']['Status'],
        "SubmittedAt": response['ChangeInfo']['SubmittedAt'].isoformat(),
        "Comment": "DNS record update request submitted successfully."
    }

    return custom_response

