import re
from http import HTTPStatus

from aws_lambda_powertools.event_handler.api_gateway import Router
from layercake.dateutils import now
from layercake.dynamodb import (
    DynamoDBPersistenceLayer,
    KeyPair,
)
from pydantic import BaseModel, ConfigDict, field_validator

from api_gateway import JSONResponse
from boto3clients import dynamodb_client
from config import USER_TABLE

router = Router()
org_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)


@router.get('/<id>/address', compress=True, tags=['Organization'])
def get_address(id: str):
    return org_layer.collection.get_item(
        KeyPair(id, 'metadata#address'),
        raise_on_error=False,
        default={},
    )


class Address(BaseModel):
    model_config = ConfigDict(str_strip_whitespace=True)

    postcode: str
    address1: str
    address2: str | None = None
    neighborhood: str
    city: str
    state: str

    @field_validator('postcode')
    @classmethod
    def _only_numbers(cls, v: str) -> str:
        return re.sub(r'\D', '', v)


@router.post('/<id>/address', compress=True, tags=['Organization'])
def post_address(id: str, payload: Address):
    now_ = now()
    address = payload.model_dump(exclude_none=True)
    org_layer.collection.put_item(
        key=KeyPair(id, 'metadata#address'),
        updated_at=now_,
        **address,
    )

    return JSONResponse(
        body=payload,
        status_code=HTTPStatus.OK,
    )
