# -*- coding: utf-8 -*-
from __future__ import annotations

import datetime
import urllib.parse
import uuid

import pydantic

from hotpocket_common.constants import AccessTokenOriginApp

from .base import BaseModelOut, ModelOut, Query


class AccessTokenOut(ModelOut):
    key: str
    origin: str
    meta: dict

    def get_parsed_origin(self) -> urllib.parse.SplitResult:
        return urllib.parse.urlsplit(self.origin)

    def get_origin_app(self) -> AccessTokenOriginApp | None:
        parsed_origin = self.get_parsed_origin()

        match parsed_origin.scheme:
            case 'safari-web-extension':
                return AccessTokenOriginApp.SAFARI_WEB_EXTENSION

            case 'chrome-extension':
                return AccessTokenOriginApp.CHROME_EXTENSION

            case 'moz-extension':
                return AccessTokenOriginApp.FIREFOX_EXTENSION

            case 'hotpocket-desktop':
                return AccessTokenOriginApp.HOTPOCKET_DESKTOP

            case 'hotpocket-mobile':
                return AccessTokenOriginApp.HOTPOCKET_MOBILE

            case _:
                return None

    def get_origin_app_id(self) -> str:
        return self.get_parsed_origin().netloc


class AccessTokensQuery(Query):
    account_uuid: uuid.UUID
    before: uuid.UUID | None = pydantic.Field(default=None)


class AccessTokenMetaUpdateIn(pydantic.BaseModel):
    version: str | None = None
    platform: str | None = None


class AuthKeyOut(ModelOut):
    account_uuid: uuid.UUID
    key: str
    consumed_at: datetime.datetime | None = None


class AccountOut(BaseModelOut):
    first_name: str
    last_name: str
    username: str
    settings: dict
