# Generated from example#OrderRepository by sql-service-codegen. Do not edit by hand.
from __future__ import annotations

import json
import uuid
from datetime import datetime
from typing import cast, override

import psycopg
from generated.example.models.order_repository_models import (
    FulfillmentState,
    FulfillmentStateDelivered,
    FulfillmentStatePending,
    FulfillmentStateShipped,
    OrderLine,
    PostalAddress,
)
from generated.example.order_repository_protocol import (
    GetOrderResult,
    OrderRepositoryServiceProtocol,
)
from generated.example.postgres.psycopg_transaction_run import run


class OrderRepositoryPsycopgService(OrderRepositoryServiceProtocol[psycopg.AsyncTransaction]):
    def __init__(self, connection: psycopg.AsyncConnection) -> None:
        super().__init__()
        self._connection = connection

    @override
    async def create_order(
        self,
        label: str,
        *,
        transaction: psycopg.AsyncTransaction | None = None,
    ) -> str:
        async def execute() -> str:
            cur = await self._connection.execute(
                """INSERT INTO orders (label) VALUES (%s) RETURNING id;""",
                (label,),
            )
            row = await cur.fetchone()
            if row is None:
                raise RuntimeError("INSERT RETURNING produced no row")
            return _read_str(row, 0)

        return await run(self._connection, transaction, execute)

    @override
    async def get_order(
        self,
        id: str,
        *,
        transaction: psycopg.AsyncTransaction | None = None,
    ) -> GetOrderResult | None:
        async def execute() -> GetOrderResult | None:
            cur = await self._connection.execute(
                """SELECT orders.id, orders.label, ol.id AS ol_id, ol.order_id AS ol_order_id, ol.sku AS ol_sku, ol.fulfillment AS ol_fulfillment, ol.ship_to AS ol_ship_to
FROM orders AS orders
LEFT JOIN order_lines AS ol ON orders.id = ol.order_id
WHERE orders.id = %s;""",
                (id,),
            )
            rows = await cur.fetchall()
            if not rows:
                return None
            row = rows[0]
            order_lines: list[OrderLine] = []
            for joined_row in rows:
                if joined_row[2] is not None:
                    order_lines.append(
                        OrderLine(
                            id=_read_str(joined_row, 2),
                            order_id=_read_str(joined_row, 3),
                            sku=_read_str(joined_row, 4),
                            fulfillment=_read_FulfillmentState(joined_row, 5),
                            ship_to=_read_PostalAddress(joined_row, 6),
                        )
                    )
            return GetOrderResult(
                id=_read_str(row, 0),
                label=_read_str(row, 1),
                order_lines=order_lines,
            )

        return await run(self._connection, transaction, execute)


def _map_json_timestamp(value: object) -> datetime:
    if isinstance(value, datetime):
        return value
    return datetime.fromisoformat(str(value))


def _dump_json_timestamp(value: datetime) -> str:
    return value.isoformat()


def _map_to_PostalAddress(data: dict[str, object]) -> PostalAddress:
    return PostalAddress(
        street=cast(str, data["street"]),
        city=cast(str, data["city"]),
    )


def _dump_PostalAddress(value: PostalAddress) -> dict[str, object]:
    return {
        "street": value.street,
        "city": value.city,
    }


def _map_to_FulfillmentState(data: dict[str, object]) -> FulfillmentState:
    present = [key for key in ("pending", "shipped", "delivered") if key in data]
    if len(present) != 1:
        raise ValueError(f"unknown FulfillmentState discriminator: {sorted(data.keys())}")
    if "pending" in data:
        return FulfillmentStatePending(
            pending=cast(str, data["pending"]),
        )
    if "shipped" in data:
        return FulfillmentStateShipped(
            shipped=_map_json_timestamp(data["shipped"]),
        )
    if "delivered" in data:
        return FulfillmentStateDelivered(
            delivered=_map_json_timestamp(data["delivered"]),
        )
    raise ValueError(f"unknown FulfillmentState discriminator: {sorted(data.keys())}")


def _dump_FulfillmentState(value: FulfillmentState) -> dict[str, object]:
    if isinstance(value, FulfillmentStatePending):
        return {"pending": value.pending}
    if isinstance(value, FulfillmentStateShipped):
        return {"shipped": _dump_json_timestamp(value.shipped)}
    if isinstance(value, FulfillmentStateDelivered):
        return {"delivered": _dump_json_timestamp(value.delivered)}
    raise TypeError(f"unsupported FulfillmentState variant: {type(value)!r}")


def _read_str(row: tuple[object, ...], index: int) -> str:
    value = row[index]
    if isinstance(value, uuid.UUID):
        return str(value)
    return cast(str, value)


def _json_bind_FulfillmentState(value: FulfillmentState) -> str:
    return json.dumps(_dump_FulfillmentState(value))


def _read_FulfillmentState(row: tuple[object, ...], index: int) -> FulfillmentState:
    value = row[index]
    if isinstance(value, dict):
        data = cast(dict[str, object], value)
    else:
        data = cast(dict[str, object], json.loads(cast(str, value)))
    return _map_to_FulfillmentState(data)


def _json_bind_PostalAddress(value: PostalAddress) -> str:
    return json.dumps(_dump_PostalAddress(value))


def _read_PostalAddress(row: tuple[object, ...], index: int) -> PostalAddress:
    value = row[index]
    if isinstance(value, dict):
        data = cast(dict[str, object], value)
    else:
        data = cast(dict[str, object], json.loads(cast(str, value)))
    return _map_to_PostalAddress(data)
