# Path: src/schemas/messages.py
# class SendMethod(str, Enum):
#     """
#     Should match SEND_METHODS sql enum
#     """
# 
#     email_mandrill = 'email-mandrill'
#     email_ses = 'email-ses'
#     email_test = 'email-test'
#     sms_messagebird = 'sms-messagebird'
#     sms_test = 'sms-test'
# 
# class SubaccountModel(BaseModel):
#     company_code: str = ...
#     company_name: str = None
# 
# Path: src/utils.py
# class AdminAuth:
#     def __init__(self, request: Request):
#         if request.headers.get('Authorization', '') != glove.settings.auth_key:
#             raise HttpForbidden('Invalid token')


import json
import logging
from buildpg.asyncpg import BuildPgConnection
from fastapi import APIRouter, Depends
from foxglove import glove
from foxglove.db.middleware import get_db
from foxglove.exceptions import HttpBadRequest, HttpConflict, HttpNotFound
from foxglove.route_class import KeepBodyAPIRoute
from httpx import Response
from starlette.responses import JSONResponse
from typing import Optional
from src.schemas.messages import SendMethod, SubaccountModel
from src.utils import AdminAuth
async def create_subaccount(method: SendMethod, m: Optional[SubaccountModel] = None):
    if method != SendMethod.email_mandrill:
        return JSONResponse({'message': f'no subaccount creation required for "{method}"'})
    assert m

    r: Response = await glove.mandrill.post(
        'subaccounts/add.json', id=m.company_code, name=m.company_name, allowed_statuses=(200, 500), timeout_=12
    )
    data = r.json()
    if r.status_code == 200:
        return JSONResponse({'message': 'subaccount created'}, status_code=201)

    assert r.status_code == 500, r.status_code
    if f'A subaccount with id {m.company_code} already exists' not in data.get('message', ''):
        return JSONResponse({'message': f'error from mandrill: {json.dumps(data, indent=2)}'}, status_code=400)

    r = await glove.mandrill.get('subaccounts/info.json', id=m.company_code, timeout_=12)
    data = r.json()
    total_sent = data['sent_total']
    if total_sent > 100:
        raise HttpConflict(
            f'subaccount already exists with {total_sent} emails sent, reuse of subaccount id not permitted'
        )
    else:
        return {
            'message': f'subaccount already exists with only {total_sent} emails sent, reuse of subaccount id permitted'
        }


@app.post('/delete-subaccount/{method}/')

# Path: src/schemas/messages.py
# class SendMethod(str, Enum):
#     """
#     Should match SEND_METHODS sql enum
#     """
# 
#     email_mandrill = 'email-mandrill'
#     email_ses = 'email-ses'
#     email_test = 'email-test'
#     sms_messagebird = 'sms-messagebird'
#     sms_test = 'sms-test'
# 
# class SubaccountModel(BaseModel):
#     company_code: str = ...
#     company_name: str = None
# 
# Path: src/utils.py
# class AdminAuth:
#     def __init__(self, request: Request):
#         if request.headers.get('Authorization', '') != glove.settings.auth_key:
#             raise HttpForbidden('Invalid token')


# Path: src/views/subaccounts.py
import json
import logging
from buildpg.asyncpg import BuildPgConnection
from fastapi import APIRouter, Depends
from foxglove import glove
from foxglove.db.middleware import get_db
from foxglove.exceptions import HttpBadRequest, HttpConflict, HttpNotFound
from foxglove.route_class import KeepBodyAPIRoute
from httpx import Response
from starlette.responses import JSONResponse
from typing import Optional
from src.schemas.messages import SendMethod, SubaccountModel
from src.utils import AdminAuth

async def create_subaccount(method: SendMethod, m: Optional[SubaccountModel] = None):
    if method != SendMethod.email_mandrill:
        return JSONResponse({'message': f'no subaccount creation required for "{method}"'})
    assert m

    r: Response = await glove.mandrill.post(
        'subaccounts/add.json', id=m.company_code, name=m.company_name, allowed_statuses=(200, 500), timeout_=12
    )
    data = r.json()
    if r.status_code == 200:
        return JSONResponse({'message': 'subaccount created'}, status_code=201)

    assert r.status_code == 500, r.status_code
    if f'A subaccount with id {m.company_code} already exists' not in data.get('message', ''):
        return JSONResponse({'message': f'error from mandrill: {json.dumps(data, indent=2)}'}, status_code=400)

    r = await glove.mandrill.get('subaccounts/info.json', id=m.company_code, timeout_=12)
    data = r.json()
    total_sent = data['sent_total']
    if total_sent > 100:
        raise HttpConflict(
            f'subaccount already exists with {total_sent} emails sent, reuse of subaccount id not permitted'
        )
    else:
        return {
            'message': f'subaccount already exists with only {total_sent} emails sent, reuse of subaccount id permitted'
        }


@app.post('/delete-subaccount/{method}/')

async def delete_subaccount(method: SendMethod, m: SubaccountModel, conn: BuildPgConnection = Depends(get_db)):