"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from __future__ import annotations
from .linktagschema import LinkTagSchema, LinkTagSchemaTypedDict
from dub.types import BaseModel, Nullable, OptionalNullable, UNSET, UNSET_SENTINEL
from enum import Enum
import pydantic
from pydantic import model_serializer
from typing import Any, Dict, List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict


class SaleCreatedEventEvent(str, Enum):
    SALE_CREATED = "sale.created"


class SaleCreatedEventCustomerTypedDict(TypedDict):
    id: str
    r"""The unique ID of the customer. You may use either the customer's `id` on Dub (obtained via `/customers` endpoint) or their `externalId` (unique ID within your system, prefixed with `ext_`, e.g. `ext_123`)."""
    name: str
    r"""Name of the customer."""
    external_id: str
    r"""Unique identifier for the customer in the client's app."""
    created_at: str
    r"""The date the customer was created (usually the signup date or trial start date)."""
    email: NotRequired[Nullable[str]]
    r"""Email of the customer."""
    avatar: NotRequired[Nullable[str]]
    r"""Avatar URL of the customer."""
    stripe_customer_id: NotRequired[Nullable[str]]
    r"""The customer's Stripe customer ID. This is useful for attributing recurring sale events to the partner who referred the customer."""
    country: NotRequired[Nullable[str]]
    r"""Country of the customer."""
    sales: NotRequired[Nullable[float]]
    r"""Total number of sales for the customer."""
    sale_amount: NotRequired[Nullable[float]]
    r"""Total amount of sales for the customer."""
    first_sale_at: NotRequired[Nullable[str]]
    r"""The date the customer made their first sale. Useful for calculating the time to first sale and LTV."""
    subscription_canceled_at: NotRequired[Nullable[str]]
    r"""The date the customer canceled their subscription. Useful for calculating LTV and churn rate."""


class SaleCreatedEventCustomer(BaseModel):
    id: str
    r"""The unique ID of the customer. You may use either the customer's `id` on Dub (obtained via `/customers` endpoint) or their `externalId` (unique ID within your system, prefixed with `ext_`, e.g. `ext_123`)."""

    name: str
    r"""Name of the customer."""

    external_id: Annotated[str, pydantic.Field(alias="externalId")]
    r"""Unique identifier for the customer in the client's app."""

    created_at: Annotated[str, pydantic.Field(alias="createdAt")]
    r"""The date the customer was created (usually the signup date or trial start date)."""

    email: OptionalNullable[str] = UNSET
    r"""Email of the customer."""

    avatar: OptionalNullable[str] = UNSET
    r"""Avatar URL of the customer."""

    stripe_customer_id: Annotated[
        OptionalNullable[str], pydantic.Field(alias="stripeCustomerId")
    ] = UNSET
    r"""The customer's Stripe customer ID. This is useful for attributing recurring sale events to the partner who referred the customer."""

    country: OptionalNullable[str] = UNSET
    r"""Country of the customer."""

    sales: OptionalNullable[float] = UNSET
    r"""Total number of sales for the customer."""

    sale_amount: Annotated[
        OptionalNullable[float], pydantic.Field(alias="saleAmount")
    ] = UNSET
    r"""Total amount of sales for the customer."""

    first_sale_at: Annotated[
        OptionalNullable[str], pydantic.Field(alias="firstSaleAt")
    ] = UNSET
    r"""The date the customer made their first sale. Useful for calculating the time to first sale and LTV."""

    subscription_canceled_at: Annotated[
        OptionalNullable[str], pydantic.Field(alias="subscriptionCanceledAt")
    ] = UNSET
    r"""The date the customer canceled their subscription. Useful for calculating LTV and churn rate."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(
            [
                "email",
                "avatar",
                "stripeCustomerId",
                "country",
                "sales",
                "saleAmount",
                "firstSaleAt",
                "subscriptionCanceledAt",
            ]
        )
        nullable_fields = set(
            [
                "email",
                "avatar",
                "stripeCustomerId",
                "country",
                "sales",
                "saleAmount",
                "firstSaleAt",
                "subscriptionCanceledAt",
            ]
        )
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


class SaleCreatedEventClickTypedDict(TypedDict):
    id: str
    timestamp: str
    url: str
    country: str
    city: str
    region: str
    continent: str
    device: str
    browser: str
    os: str
    referer: str
    referer_url: str
    qr: bool
    ip: str
    trigger: NotRequired[Nullable[str]]


class SaleCreatedEventClick(BaseModel):
    id: str

    timestamp: str

    url: str

    country: str

    city: str

    region: str

    continent: str

    device: str

    browser: str

    os: str

    referer: str

    referer_url: Annotated[str, pydantic.Field(alias="refererUrl")]

    qr: bool

    ip: str

    trigger: OptionalNullable[str] = UNSET

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["trigger"])
        nullable_fields = set(["trigger"])
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


class SaleCreatedEventTestVariantsTypedDict(TypedDict):
    url: str
    percentage: float


class SaleCreatedEventTestVariants(BaseModel):
    url: str

    percentage: float


class SaleCreatedEventLinkTypedDict(TypedDict):
    id: str
    r"""The unique ID of the short link."""
    domain: str
    r"""The domain of the short link. If not provided, the primary domain for the workspace will be used (or `dub.sh` if the workspace has no domains)."""
    key: str
    r"""The short link slug. If not provided, a random 7-character slug will be generated."""
    url: str
    track_conversion: bool
    external_id: Nullable[str]
    r"""The ID of the link in your database. If set, it can be used to identify the link in future API requests (must be prefixed with 'ext_' when passed as a query parameter). This key is unique across your workspace."""
    tenant_id: Nullable[str]
    r"""The ID of the tenant that created the link inside your system. If set, it can be used to fetch all links for a tenant."""
    program_id: Nullable[str]
    r"""The ID of the program the short link is associated with."""
    partner_id: Nullable[str]
    r"""The ID of the partner the short link is associated with."""
    archived: bool
    expires_at: str
    expired_url: Nullable[str]
    disabled_at: str
    password: Nullable[str]
    r"""The password required to access the destination URL of the short link."""
    proxy: bool
    title: Nullable[str]
    r"""The title of the short link. Will be used for Custom Link Previews if `proxy` is true."""
    description: Nullable[str]
    r"""The description of the short link. Will be used for Custom Link Previews if `proxy` is true."""
    image: Nullable[str]
    r"""The image of the short link. Will be used for Custom Link Previews if `proxy` is true."""
    video: Nullable[str]
    r"""The custom link preview video (og:video). Will be used for Custom Link Previews if `proxy` is true. Learn more: https://d.to/og"""
    rewrite: bool
    do_index: bool
    ios: Nullable[str]
    r"""The iOS destination URL for the short link for iOS device targeting."""
    android: Nullable[str]
    r"""The Android destination URL for the short link for Android device targeting."""
    geo: Nullable[Dict[str, str]]
    r"""Geo targeting information for the short link in JSON format `{[COUNTRY]: https://example.com }`. See https://d.to/geo for more information."""
    public_stats: bool
    tags: Nullable[List[LinkTagSchemaTypedDict]]
    r"""The tags assigned to the short link."""
    folder_id: Nullable[str]
    r"""The unique ID of the folder assigned to the short link."""
    webhook_ids: List[str]
    r"""The IDs of the webhooks that the short link is associated with."""
    comments: Nullable[str]
    r"""The comments for the short link."""
    short_link: str
    r"""The full URL of the short link, including the https protocol (e.g. `https://dub.sh/try`)."""
    qr_code: str
    r"""The full URL of the QR code for the short link (e.g. `https://api.dub.co/qr?url=https://dub.sh/try`)."""
    utm_source: Nullable[str]
    r"""The UTM source of the short link."""
    utm_medium: Nullable[str]
    r"""The UTM medium of the short link."""
    utm_campaign: Nullable[str]
    r"""The UTM campaign of the short link."""
    utm_term: Nullable[str]
    r"""The UTM term of the short link."""
    utm_content: Nullable[str]
    r"""The UTM content of the short link."""
    test_started_at: str
    test_completed_at: str
    user_id: Nullable[str]
    workspace_id: str
    r"""The workspace ID of the short link."""
    last_clicked: str
    created_at: str
    updated_at: str
    tag_id: Nullable[str]
    r"""Deprecated: Use `tags` instead. The unique ID of the tag assigned to the short link."""
    project_id: str
    r"""Deprecated: Use `workspaceId` instead. The project ID of the short link."""
    test_variants: NotRequired[Nullable[List[SaleCreatedEventTestVariantsTypedDict]]]
    r"""An array of A/B test URLs and the percentage of traffic to send to each URL."""
    clicks: NotRequired[float]
    r"""The number of clicks on the short link."""
    leads: NotRequired[float]
    r"""The number of leads the short link has generated."""
    conversions: NotRequired[float]
    r"""The number of leads that converted to paying customers."""
    sales: NotRequired[float]
    r"""The total number of sales (includes recurring sales) generated by the short link."""
    sale_amount: NotRequired[float]
    r"""The total dollar value of sales (in cents) generated by the short link."""


class SaleCreatedEventLink(BaseModel):
    id: str
    r"""The unique ID of the short link."""

    domain: str
    r"""The domain of the short link. If not provided, the primary domain for the workspace will be used (or `dub.sh` if the workspace has no domains)."""

    key: str
    r"""The short link slug. If not provided, a random 7-character slug will be generated."""

    url: str

    track_conversion: Annotated[bool, pydantic.Field(alias="trackConversion")]

    external_id: Annotated[Nullable[str], pydantic.Field(alias="externalId")]
    r"""The ID of the link in your database. If set, it can be used to identify the link in future API requests (must be prefixed with 'ext_' when passed as a query parameter). This key is unique across your workspace."""

    tenant_id: Annotated[Nullable[str], pydantic.Field(alias="tenantId")]
    r"""The ID of the tenant that created the link inside your system. If set, it can be used to fetch all links for a tenant."""

    program_id: Annotated[Nullable[str], pydantic.Field(alias="programId")]
    r"""The ID of the program the short link is associated with."""

    partner_id: Annotated[Nullable[str], pydantic.Field(alias="partnerId")]
    r"""The ID of the partner the short link is associated with."""

    archived: bool

    expires_at: Annotated[str, pydantic.Field(alias="expiresAt")]

    expired_url: Annotated[Nullable[str], pydantic.Field(alias="expiredUrl")]

    disabled_at: Annotated[str, pydantic.Field(alias="disabledAt")]

    password: Nullable[str]
    r"""The password required to access the destination URL of the short link."""

    proxy: bool

    title: Nullable[str]
    r"""The title of the short link. Will be used for Custom Link Previews if `proxy` is true."""

    description: Nullable[str]
    r"""The description of the short link. Will be used for Custom Link Previews if `proxy` is true."""

    image: Nullable[str]
    r"""The image of the short link. Will be used for Custom Link Previews if `proxy` is true."""

    video: Nullable[str]
    r"""The custom link preview video (og:video). Will be used for Custom Link Previews if `proxy` is true. Learn more: https://d.to/og"""

    rewrite: bool

    do_index: Annotated[bool, pydantic.Field(alias="doIndex")]

    ios: Nullable[str]
    r"""The iOS destination URL for the short link for iOS device targeting."""

    android: Nullable[str]
    r"""The Android destination URL for the short link for Android device targeting."""

    geo: Nullable[Dict[str, str]]
    r"""Geo targeting information for the short link in JSON format `{[COUNTRY]: https://example.com }`. See https://d.to/geo for more information."""

    public_stats: Annotated[bool, pydantic.Field(alias="publicStats")]

    tags: Nullable[List[LinkTagSchema]]
    r"""The tags assigned to the short link."""

    folder_id: Annotated[Nullable[str], pydantic.Field(alias="folderId")]
    r"""The unique ID of the folder assigned to the short link."""

    webhook_ids: Annotated[List[str], pydantic.Field(alias="webhookIds")]
    r"""The IDs of the webhooks that the short link is associated with."""

    comments: Nullable[str]
    r"""The comments for the short link."""

    short_link: Annotated[str, pydantic.Field(alias="shortLink")]
    r"""The full URL of the short link, including the https protocol (e.g. `https://dub.sh/try`)."""

    qr_code: Annotated[str, pydantic.Field(alias="qrCode")]
    r"""The full URL of the QR code for the short link (e.g. `https://api.dub.co/qr?url=https://dub.sh/try`)."""

    utm_source: Nullable[str]
    r"""The UTM source of the short link."""

    utm_medium: Nullable[str]
    r"""The UTM medium of the short link."""

    utm_campaign: Nullable[str]
    r"""The UTM campaign of the short link."""

    utm_term: Nullable[str]
    r"""The UTM term of the short link."""

    utm_content: Nullable[str]
    r"""The UTM content of the short link."""

    test_started_at: Annotated[str, pydantic.Field(alias="testStartedAt")]

    test_completed_at: Annotated[str, pydantic.Field(alias="testCompletedAt")]

    user_id: Annotated[Nullable[str], pydantic.Field(alias="userId")]

    workspace_id: Annotated[str, pydantic.Field(alias="workspaceId")]
    r"""The workspace ID of the short link."""

    last_clicked: Annotated[str, pydantic.Field(alias="lastClicked")]

    created_at: Annotated[str, pydantic.Field(alias="createdAt")]

    updated_at: Annotated[str, pydantic.Field(alias="updatedAt")]

    tag_id: Annotated[
        Nullable[str],
        pydantic.Field(
            deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.",
            alias="tagId",
        ),
    ]
    r"""Deprecated: Use `tags` instead. The unique ID of the tag assigned to the short link."""

    project_id: Annotated[
        str,
        pydantic.Field(
            deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.",
            alias="projectId",
        ),
    ]
    r"""Deprecated: Use `workspaceId` instead. The project ID of the short link."""

    test_variants: Annotated[
        OptionalNullable[List[SaleCreatedEventTestVariants]],
        pydantic.Field(alias="testVariants"),
    ] = UNSET
    r"""An array of A/B test URLs and the percentage of traffic to send to each URL."""

    clicks: Optional[float] = 0
    r"""The number of clicks on the short link."""

    leads: Optional[float] = 0
    r"""The number of leads the short link has generated."""

    conversions: Optional[float] = 0
    r"""The number of leads that converted to paying customers."""

    sales: Optional[float] = 0
    r"""The total number of sales (includes recurring sales) generated by the short link."""

    sale_amount: Annotated[Optional[float], pydantic.Field(alias="saleAmount")] = 0
    r"""The total dollar value of sales (in cents) generated by the short link."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(
            ["testVariants", "clicks", "leads", "conversions", "sales", "saleAmount"]
        )
        nullable_fields = set(
            [
                "externalId",
                "tenantId",
                "programId",
                "partnerId",
                "expiredUrl",
                "password",
                "title",
                "description",
                "image",
                "video",
                "ios",
                "android",
                "geo",
                "tags",
                "folderId",
                "comments",
                "utm_source",
                "utm_medium",
                "utm_campaign",
                "utm_term",
                "utm_content",
                "testVariants",
                "userId",
                "tagId",
            ]
        )
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


class SaleTypedDict(TypedDict):
    amount: float
    currency: str
    payment_processor: str
    invoice_id: Nullable[str]


class Sale(BaseModel):
    amount: float

    currency: str

    payment_processor: Annotated[str, pydantic.Field(alias="paymentProcessor")]

    invoice_id: Annotated[Nullable[str], pydantic.Field(alias="invoiceId")]

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)

            if val != UNSET_SENTINEL:
                m[k] = val

        return m


class SaleCreatedEventPartnerTypedDict(TypedDict):
    id: str
    r"""The partner's unique ID on Dub."""
    name: str
    r"""The partner's full legal name."""
    email: Nullable[str]
    r"""The partner's email address. Should be a unique value across Dub."""
    image: Nullable[str]
    r"""The partner's avatar image."""
    payouts_enabled_at: Nullable[str]
    r"""The date when the partner enabled payouts."""
    country: Nullable[str]
    r"""The partner's country (required for tax purposes)."""
    total_clicks: float
    total_leads: float
    total_conversions: float
    total_sales: float
    total_sale_amount: float
    total_commissions: float
    group_id: NotRequired[Nullable[str]]


class SaleCreatedEventPartner(BaseModel):
    id: str
    r"""The partner's unique ID on Dub."""

    name: str
    r"""The partner's full legal name."""

    email: Nullable[str]
    r"""The partner's email address. Should be a unique value across Dub."""

    image: Nullable[str]
    r"""The partner's avatar image."""

    payouts_enabled_at: Annotated[
        Nullable[str], pydantic.Field(alias="payoutsEnabledAt")
    ]
    r"""The date when the partner enabled payouts."""

    country: Nullable[str]
    r"""The partner's country (required for tax purposes)."""

    total_clicks: Annotated[float, pydantic.Field(alias="totalClicks")]

    total_leads: Annotated[float, pydantic.Field(alias="totalLeads")]

    total_conversions: Annotated[float, pydantic.Field(alias="totalConversions")]

    total_sales: Annotated[float, pydantic.Field(alias="totalSales")]

    total_sale_amount: Annotated[float, pydantic.Field(alias="totalSaleAmount")]

    total_commissions: Annotated[float, pydantic.Field(alias="totalCommissions")]

    group_id: Annotated[OptionalNullable[str], pydantic.Field(alias="groupId")] = UNSET

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["groupId"])
        nullable_fields = set(
            ["email", "image", "payoutsEnabledAt", "country", "groupId"]
        )
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


class SaleCreatedEventDataTypedDict(TypedDict):
    event_name: str
    customer: SaleCreatedEventCustomerTypedDict
    click: SaleCreatedEventClickTypedDict
    link: SaleCreatedEventLinkTypedDict
    sale: SaleTypedDict
    partner: NotRequired[Nullable[SaleCreatedEventPartnerTypedDict]]
    metadata: NotRequired[Nullable[Dict[str, Any]]]


class SaleCreatedEventData(BaseModel):
    event_name: Annotated[str, pydantic.Field(alias="eventName")]

    customer: SaleCreatedEventCustomer

    click: SaleCreatedEventClick

    link: SaleCreatedEventLink

    sale: Sale

    partner: OptionalNullable[SaleCreatedEventPartner] = UNSET

    metadata: OptionalNullable[Dict[str, Any]] = UNSET

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = set(["partner", "metadata"])
        nullable_fields = set(["partner", "metadata"])
        serialized = handler(self)
        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            is_nullable_and_explicitly_set = (
                k in nullable_fields
                and (self.__pydantic_fields_set__.intersection({n}))  # pylint: disable=no-member
            )

            if val != UNSET_SENTINEL:
                if (
                    val is not None
                    or k not in optional_fields
                    or is_nullable_and_explicitly_set
                ):
                    m[k] = val

        return m


class SaleCreatedEventTypedDict(TypedDict):
    r"""Triggered when a sale is created."""

    id: str
    event: SaleCreatedEventEvent
    created_at: str
    data: SaleCreatedEventDataTypedDict


class SaleCreatedEvent(BaseModel):
    r"""Triggered when a sale is created."""

    id: str

    event: SaleCreatedEventEvent

    created_at: Annotated[str, pydantic.Field(alias="createdAt")]

    data: SaleCreatedEventData
