import sys

if "/service_app_banks" not in list(sys.path):
    sys.path.append("/service_app_banks")

from api_services.email.service import send_email
from api_library.date_time_actions.date_functions import client_arrow
from databases import AccountRecords


def send_mail_to_users_that_have_received_email_from_banks():
    print("Service is booting up")
    print("Sending mail to users that have received email from banks")

    # account_records = AccountRecords.query.filter(
    #     AccountRecords.bank_date >= datetime(
    #         today.year, today.month, today.day - int(day_offset), 23, 59, 59)   # AccountRecords.bank_date >= datetime(2024, 9, 5, 23, 59, 59)
    # ).order_by(
    #     AccountRecords.bank_date.desc(), AccountRecords.bank_reference_code.desc()
    # ).all()

    # if not account_records:
    account_records = (
        AccountRecords.query.filter()
        .order_by(
            AccountRecords.bank_date.desc(), AccountRecords.bank_reference_code.desc()
        )
        .limit(3)
        .all()
    )

    today, first_record, second_record, balance_error = (
        client_arrow.now(),
        account_records[0],
        account_records[1],
        False,
    )
    second_balance = first_record.bank_balance - first_record.currency_value
    if second_balance != second_record.bank_balance:
        balance_error = True

    send_to = "karatay@mehmetkaratay.com.tr"
    styles = """<style>
            body {
                font-family: Arial, sans-serif;
                margin: 20px;
            }
            table {
                width: 100%;
                border-collapse: collapse;
            }
            table, th, td {
                border: 1px solid black;
            }
            th, td {
                padding: 10px;
                text-align: left;
            }
            th {
                background-color: #f2f2f2;
            }
        </style>
    """
    table_data = ""
    table_headers = """
        <thead>
            <tr>
                <th>Ulaştığı Tarih</th>
                <th>Banka Transaksiyonu Ek Bilgi</th>
                <th>Aktarım Değeri</th>
            </tr>
        </thead>
    """
    table_row_add = (
        lambda date, comment, currency: f"""
        <thead>
            <tr>
                <td>{date}</td>
                <td>{comment}</td>
                <td>{"%.2f" % currency}</td>
            </tr>
        </thead>
    """
    )
    if not account_records:
        return

    for account_record in account_records:
        table_data += table_row_add(
            account_record.bank_date,
            account_record.process_comment,
            account_record.currency_value,
        )

    html_template = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gelen Banka Kayıtları</title>
        {styles}
    </head>
    <body>
        <h1>Günaydın, Admin</h1>
        <br>
        <p>Banka Kayıtları : {str(today)} </p>
        <p><b>Son Bakiye : {"%.2f" % account_records[0].bank_balance} </b></p>
        <p><b>{"Status : İkinci Bakiye Hatalı" if balance_error else "Status :OK"}</b></p>
        <br>
        <table>
            {table_headers}
            <tbody>
                {table_data}
            </tbody>
        </table>
        <br>
        <p>Teşekkür ederiz,<br>Evyos Yönetim<br>Saygılarımızla</p>
    </body>
    </html>
    """
    subject = f"{str(today.date())} Gunes Apt. Cari Durum Bilgilendirme Raporu"
    try:
        send_email(
            subject=subject,
            receivers=[send_to],
            html=html_template,
        )
        print(f"Email is sent to : {send_to}. BB")
        return
    except Exception as e:
        print(f"Error: {e}")
    print("Email is not sent")


if __name__ == "__main__":
    send_mail_to_users_that_have_received_email_from_banks()
