from typing import List
from uuid import UUID

import inject
from sqlmodel import Session, select

from src.core.events import EventDescription
from src.core.helpers.exceptions import DatabaseError, NotAuthorizedError, NotFoundError
from src.core.models import Client, Context, CreateClient, QueryClient, UpdateClient
from src.core.services import Streamer


@inject.params(streamer=Streamer)
def create(session: Session, schema: CreateClient, context: Context, streamer: Streamer) -> Client:
    if session.exec(select(Client).where(Client.email == schema.email)).first():
        raise DatabaseError("Já existe um cliente cadastrado com o email: %s" % schema.email)

    if session.exec(select(Client).where(Client.phone == schema.phone)).first():
        raise DatabaseError("Já existe um cliente cadastrado com o telefone: %s" % schema.phone)

    client = Client(**schema.dict(), owner_id=context.user_id)
    session.add(client)
    session.commit()
    streamer.send_event(EventDescription.CREATE_USER, context=context, client=client.dict())

    return client


def get_all(session: Session, query_schema: QueryClient, context: Context) -> List[Client]:
    args = []

    if not context.user_is_super_user:
        args.append(Client.owner_id == context.user_id)

    return session.exec(