from __future__ import annotations

from sqlalchemy import Boolean, Float, Index, Integer, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column

from services.shared.sql_models import Base


class TenantSalesSettingsRow(Base):
    __tablename__ = "tenant_sales_settings"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    tenant_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    default_pipeline_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    default_language: Mapped[str] = mapped_column(String(16), default="ru", index=True)
    default_currency: Mapped[str] = mapped_column(String(16), default="KZT", index=True)
    enabled_text_channels_json: Mapped[str] = mapped_column(Text, default="[]")
    enabled_voice_channels_json: Mapped[str] = mapped_column(Text, default="[]")
    payment_provider_settings_json: Mapped[str] = mapped_column(Text, default="{}")
    document_settings_json: Mapped[str] = mapped_column(Text, default="{}")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class TenantIntegrationRow(Base):
    __tablename__ = "tenant_integrations"
    __table_args__ = (
        Index("idx_tenant_integrations_provider_account", "provider_type", "provider_name", "provider_account_id"),
        Index("idx_tenant_integrations_external_identifier", "provider_type", "provider_name", "external_identifier"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    integration_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    provider_type: Mapped[str] = mapped_column(String(64), index=True)
    provider_name: Mapped[str] = mapped_column(String(64), index=True)
    provider_account_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    external_identifier: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    settings_json: Mapped[str] = mapped_column(Text, default="{}")
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesPipelineRow(Base):
    __tablename__ = "sales_pipelines"
    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_sales_pipelines_tenant_code"),
        Index("idx_sales_pipelines_tenant_default", "tenant_id", "is_default", "is_active"),
        Index(
            "uq_sales_pipelines_one_default_per_tenant",
            "tenant_id",
            unique=True,
            sqlite_where=text("is_default = 1"),
            postgresql_where=text("is_default IS TRUE"),
        ),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    pipeline_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    code: Mapped[str] = mapped_column(String(64), index=True)
    name: Mapped[str] = mapped_column(String(256))
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    is_default: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesPipelineStageRow(Base):
    __tablename__ = "sales_pipeline_stages"
    __table_args__ = (
        UniqueConstraint("tenant_id", "pipeline_id", "code", name="uq_sales_pipeline_stages_tenant_pipeline_code"),
        Index("idx_sales_pipeline_stages_pipeline_order", "tenant_id", "pipeline_id", "sort_order"),
        Index("idx_sales_pipeline_stages_tenant_active", "tenant_id", "is_active"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    stage_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    pipeline_id: Mapped[str] = mapped_column(String(64), index=True)
    code: Mapped[str] = mapped_column(String(64), index=True)
    name: Mapped[str] = mapped_column(String(256))
    category: Mapped[str] = mapped_column(String(64), index=True)
    sort_order: Mapped[int] = mapped_column(Integer, default=0, index=True)
    is_terminal: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
    is_system: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesLeadRow(Base):
    __tablename__ = "sales_leads"
    __table_args__ = (
        Index("idx_sales_leads_tenant_status_score", "tenant_id", "status", "lead_score"),
        Index("idx_sales_leads_phone_email", "phone", "email"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    lead_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    source_type: Mapped[str] = mapped_column(String(64), index=True)
    source_channel: Mapped[str] = mapped_column(String(32), index=True)
    source_campaign_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    full_name: Mapped[str] = mapped_column(String(256), index=True)
    company_name: Mapped[str | None] = mapped_column(String(256), nullable=True, index=True)
    phone: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    email: Mapped[str | None] = mapped_column(String(256), nullable=True, index=True)
    messenger_handles_json: Mapped[str] = mapped_column(Text, default="{}")
    lead_temperature: Mapped[str] = mapped_column(String(16), index=True)
    lead_score: Mapped[float] = mapped_column(Float, default=50.0, index=True)
    customer_type: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    segment_type: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    initial_need_summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    preferred_channel: Mapped[str] = mapped_column(String(32), index=True)
    assigned_agent_type: Mapped[str] = mapped_column(String(32), index=True)
    status: Mapped[str] = mapped_column(String(32), index=True)
    crm_customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesDealRow(Base):
    __tablename__ = "sales_deals"
    __table_args__ = (
        Index("idx_sales_deals_tenant_stage_status", "tenant_id", "stage_id", "status"),
        Index("idx_sales_deals_customer_channel", "customer_id", "current_channel"),
        Index("idx_sales_deals_next_action", "next_action_at", "status"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    deal_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    lead_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    pipeline_id: Mapped[str] = mapped_column(String(64), default="", index=True)
    stage_id: Mapped[str] = mapped_column(String(64), index=True)
    scenario_type: Mapped[str] = mapped_column(String(64), index=True)
    priority: Mapped[int] = mapped_column(Integer, default=3, index=True)
    title: Mapped[str] = mapped_column(String(512))
    need_summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    product_context_json: Mapped[str] = mapped_column(Text, default="{}")
    estimated_amount: Mapped[float | None] = mapped_column(Float, nullable=True)
    final_amount: Mapped[float | None] = mapped_column(Float, nullable=True)
    currency: Mapped[str] = mapped_column(String(16), default="KZT")
    payment_model: Mapped[str | None] = mapped_column(String(64), nullable=True)
    document_required: Mapped[bool] = mapped_column(Boolean, default=True)
    payment_required: Mapped[bool] = mapped_column(Boolean, default=True)
    assigned_human_user_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    assigned_ai_orchestrator_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    preferred_channel: Mapped[str] = mapped_column(String(32), index=True)
    current_channel: Mapped[str] = mapped_column(String(32), index=True)
    status: Mapped[str] = mapped_column(String(32), index=True, default="active")
    won_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    lost_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    close_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    next_action_type: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    next_action_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    last_contact_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    closed_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesCommunicationSessionRow(Base):
    __tablename__ = "sales_communication_sessions"
    __table_args__ = (
        Index("idx_sales_comm_deal_started", "deal_id", "started_at"),
        Index("idx_sales_comm_channel_status", "channel_type", "status"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    communication_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    lead_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    channel_type: Mapped[str] = mapped_column(String(16), index=True)
    channel_provider: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
    direction: Mapped[str] = mapped_column(String(16), index=True)
    agent_type: Mapped[str] = mapped_column(String(32), index=True)
    started_at: Mapped[str] = mapped_column(String(64), index=True)
    ended_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    duration_sec: Mapped[int | None] = mapped_column(Integer, nullable=True)
    subject: Mapped[str | None] = mapped_column(String(512), nullable=True)
    status: Mapped[str] = mapped_column(String(32), index=True, default="active")
    summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    transcript_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    next_action_type: Mapped[str | None] = mapped_column(String(128), nullable=True)
    next_action_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    sentiment: Mapped[str | None] = mapped_column(String(32), nullable=True)
    result_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
    metadata_json: Mapped[str] = mapped_column(Text, default="{}")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesMessageRow(Base):
    __tablename__ = "sales_messages"
    __table_args__ = (
        Index("idx_sales_messages_deal_sent", "deal_id", "sent_at"),
        Index("idx_sales_messages_ext_id", "channel_provider", "external_message_id"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    message_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    communication_id: Mapped[str] = mapped_column(String(64), index=True)
    sender_type: Mapped[str] = mapped_column(String(32), index=True)
    sender_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    channel_provider: Mapped[str] = mapped_column(String(32), index=True)
    external_message_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    body: Mapped[str] = mapped_column(Text)
    attachments_json: Mapped[str] = mapped_column(Text, default="[]")
    delivery_status: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
    read_status: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
    message_metadata_json: Mapped[str] = mapped_column(Text, default="{}")
    sent_at: Mapped[str] = mapped_column(String(64), index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesCallRow(Base):
    __tablename__ = "sales_calls"
    __table_args__ = (
        Index("idx_sales_calls_deal_started", "deal_id", "started_at"),
        Index("idx_sales_calls_ext_provider", "provider", "external_call_id"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    call_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    communication_id: Mapped[str] = mapped_column(String(64), index=True)
    phone_number: Mapped[str] = mapped_column(String(64), index=True)
    direction: Mapped[str] = mapped_column(String(16), index=True)
    provider: Mapped[str] = mapped_column(String(64), index=True)
    external_call_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    recording_url: Mapped[str | None] = mapped_column(Text, nullable=True)
    transcript_status: Mapped[str] = mapped_column(String(32), index=True, default="pending")
    transcript_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    call_status: Mapped[str] = mapped_column(String(32), index=True, default="started")
    summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    started_at: Mapped[str] = mapped_column(String(64), index=True)
    ended_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    duration_sec: Mapped[int | None] = mapped_column(Integer, nullable=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesTranscriptRow(Base):
    __tablename__ = "sales_transcripts"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    transcript_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    call_id: Mapped[str] = mapped_column(String(64), index=True)
    language: Mapped[str] = mapped_column(String(16), index=True, default="ru")
    transcript_text: Mapped[str] = mapped_column(Text)
    diarization_json: Mapped[str] = mapped_column(Text, default="{}")
    extracted_entities_json: Mapped[str] = mapped_column(Text, default="{}")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesNoteRow(Base):
    __tablename__ = "sales_notes"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    note_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    author_type: Mapped[str] = mapped_column(String(32), index=True)
    author_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    note_type: Mapped[str] = mapped_column(String(64), index=True)
    content: Mapped[str] = mapped_column(Text)
    source_type: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    source_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    archived_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)


class SalesOfferRow(Base):
    __tablename__ = "sales_offers"
    __table_args__ = (
        Index("idx_sales_offers_deal_status", "deal_id", "status"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    offer_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    offer_type: Mapped[str] = mapped_column(String(32), index=True)
    title: Mapped[str] = mapped_column(String(256))
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    line_items_json: Mapped[str] = mapped_column(Text, default="[]")
    pricing_json: Mapped[str] = mapped_column(Text, default="{}")
    total_amount: Mapped[float] = mapped_column(Float, default=0)
    currency: Mapped[str] = mapped_column(String(16), default="KZT")
    validity_until: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    status: Mapped[str] = mapped_column(String(32), index=True, default="draft")
    rendered_document_url: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_by_type: Mapped[str] = mapped_column(String(32), default="text_ai")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesConditionRow(Base):
    __tablename__ = "sales_conditions"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    condition_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    product_name: Mapped[str | None] = mapped_column(String(256), nullable=True)
    service_name: Mapped[str | None] = mapped_column(String(256), nullable=True)
    quantity: Mapped[float | None] = mapped_column(Float, nullable=True)
    unit: Mapped[str | None] = mapped_column(String(32), nullable=True)
    delivery_mode: Mapped[str | None] = mapped_column(String(64), nullable=True)
    execution_date: Mapped[str | None] = mapped_column(String(64), nullable=True)
    start_date: Mapped[str | None] = mapped_column(String(64), nullable=True)
    end_date: Mapped[str | None] = mapped_column(String(64), nullable=True)
    payment_terms: Mapped[str | None] = mapped_column(Text, nullable=True)
    custom_terms_json: Mapped[str] = mapped_column(Text, default="{}")
    agreed_price: Mapped[float | None] = mapped_column(Float, nullable=True)
    currency: Mapped[str] = mapped_column(String(16), default="KZT")
    confirmed_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesCounterpartyRow(Base):
    __tablename__ = "sales_counterparties"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    counterparty_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    company_name: Mapped[str | None] = mapped_column(String(256), nullable=True)
    full_name: Mapped[str | None] = mapped_column(String(256), nullable=True)
    bin_iin: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    address: Mapped[str | None] = mapped_column(Text, nullable=True)
    bank_details_json: Mapped[str] = mapped_column(Text, default="{}")
    signer_name: Mapped[str | None] = mapped_column(String(256), nullable=True)
    signer_role: Mapped[str | None] = mapped_column(String(128), nullable=True)
    signer_basis: Mapped[str | None] = mapped_column(String(256), nullable=True)
    email_for_docs: Mapped[str | None] = mapped_column(String(256), nullable=True)
    phone_for_docs: Mapped[str | None] = mapped_column(String(64), nullable=True)
    completeness_status: Mapped[str] = mapped_column(String(32), index=True, default="draft")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesDocumentRow(Base):
    __tablename__ = "sales_documents"
    __table_args__ = (
        Index("idx_sales_documents_deal_status", "deal_id", "status"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    document_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    document_type: Mapped[str] = mapped_column(String(64), index=True)
    template_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    version: Mapped[int] = mapped_column(Integer, default=1)
    status: Mapped[str] = mapped_column(String(32), index=True, default="draft")
    file_url: Mapped[str | None] = mapped_column(Text, nullable=True)
    rendered_payload_json: Mapped[str] = mapped_column(Text, default="{}")
    external_sign_provider_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    signed_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesInvoiceRow(Base):
    __tablename__ = "sales_invoices"
    __table_args__ = (
        Index("idx_sales_invoices_deal_status_due", "deal_id", "status", "due_date"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    invoice_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    invoice_number: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    basis_document_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    amount: Mapped[float] = mapped_column(Float, default=0)
    currency: Mapped[str] = mapped_column(String(16), default="KZT")
    due_date: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    status: Mapped[str] = mapped_column(String(32), index=True, default="draft")
    payment_link: Mapped[str | None] = mapped_column(Text, nullable=True)
    line_items_json: Mapped[str] = mapped_column(Text, default="[]")
    metadata_json: Mapped[str] = mapped_column(Text, default="{}")
    issued_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    paid_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesPaymentRow(Base):
    __tablename__ = "sales_payments"
    __table_args__ = (
        Index("idx_sales_payments_deal_status", "deal_id", "status"),
        Index(
            "idx_sales_payments_tenant_external_payment_unique",
            "tenant_id",
            "payment_provider",
            "external_payment_id",
            unique=True,
            sqlite_where=text("external_payment_id IS NOT NULL"),
            postgresql_where=text("external_payment_id IS NOT NULL"),
        ),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    payment_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    invoice_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    payment_provider: Mapped[str | None] = mapped_column(String(64), nullable=True)
    external_payment_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    amount: Mapped[float] = mapped_column(Float, default=0)
    currency: Mapped[str] = mapped_column(String(16), default="KZT")
    status: Mapped[str] = mapped_column(String(32), index=True, default="pending")
    paid_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    payment_method: Mapped[str | None] = mapped_column(String(64), nullable=True)
    failure_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    metadata_json: Mapped[str] = mapped_column(Text, default="{}")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesPaymentWebhookEventRow(Base):
    __tablename__ = "sales_payment_webhook_events"
    __table_args__ = (
        Index("idx_sales_payment_webhook_events_received", "tenant_id", "received_at"),
        Index("idx_sales_payment_webhook_events_payment", "tenant_id", "payment_provider", "external_payment_id"),
        Index(
            "idx_sales_payment_webhook_events_external_event_unique",
            "tenant_id",
            "payment_provider",
            "external_event_id",
            unique=True,
            sqlite_where=text("external_event_id IS NOT NULL"),
            postgresql_where=text("external_event_id IS NOT NULL"),
        ),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    payment_provider: Mapped[str] = mapped_column(String(64), index=True)
    provider_account_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    external_event_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    external_payment_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    event_type: Mapped[str] = mapped_column(String(128), index=True)
    event_status: Mapped[str] = mapped_column(String(32), index=True, default="received")
    signature_status: Mapped[str] = mapped_column(String(32), index=True, default="unchecked")
    raw_payload_hash: Mapped[str] = mapped_column(String(64), index=True)
    normalized_payload_json: Mapped[str] = mapped_column(Text, default="{}")
    headers_json: Mapped[str] = mapped_column(Text, default="{}")
    received_at: Mapped[str] = mapped_column(String(64), index=True)
    processed_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesStageHistoryRow(Base):
    __tablename__ = "sales_stage_history"
    __table_args__ = (
        Index("idx_sales_stage_history_deal_changed", "deal_id", "changed_at"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    history_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    from_stage_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
    to_stage_id: Mapped[str] = mapped_column(String(64), index=True)
    changed_by_type: Mapped[str] = mapped_column(String(32), index=True)
    changed_by_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    changed_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesEscalationRow(Base):
    __tablename__ = "sales_escalations"
    __table_args__ = (
        Index("idx_sales_escalations_deal_status", "deal_id", "status"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    escalation_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    escalation_type: Mapped[str] = mapped_column(String(64), index=True)
    reason: Mapped[str] = mapped_column(Text)
    severity: Mapped[str] = mapped_column(String(16), index=True)
    status: Mapped[str] = mapped_column(String(32), index=True, default="open")
    assigned_to_user_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    assigned_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    started_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    resolved_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    canceled_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    resolution_code: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    resolution_summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    sla_due_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    source_channel: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
    source_communication_session_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    source_automation_task_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    updated_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)


class SalesAutomationTaskRow(Base):
    __tablename__ = "sales_automation_tasks"
    __table_args__ = (
        Index("idx_sales_tasks_run_status", "run_at", "status"),
        Index("idx_sales_tasks_lock", "status", "locked_at", "locked_by"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    task_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    task_type: Mapped[str] = mapped_column(String(64), index=True)
    payload_json: Mapped[str] = mapped_column(Text, default="{}")
    run_at: Mapped[str] = mapped_column(String(64), index=True)
    status: Mapped[str] = mapped_column(String(32), index=True, default="pending")
    retry_count: Mapped[int] = mapped_column(Integer, default=0)
    max_retries: Mapped[int] = mapped_column(Integer, default=3)
    locked_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    locked_by: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    completed_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    failed_at: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesChannelSwitchRow(Base):
    __tablename__ = "sales_channel_switches"
    __table_args__ = (
        Index("idx_sales_channel_switches_deal_switched", "deal_id", "switched_at"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    switch_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    communication_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    communication_session_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    previous_communication_session_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    new_communication_session_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    from_channel: Mapped[str] = mapped_column(String(32), index=True)
    to_channel: Mapped[str] = mapped_column(String(32), index=True)
    reason_code: Mapped[str] = mapped_column(String(64), default="human_decision", index=True)
    reason_text: Mapped[str | None] = mapped_column(Text, nullable=True)
    reason_for_channel_switch: Mapped[str] = mapped_column(Text)
    initiated_by_type: Mapped[str] = mapped_column(String(32), default="human", index=True)
    initiated_by_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    source_type: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    source_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
    recommended_by_task_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    switched_at: Mapped[str] = mapped_column(String(64), index=True)
    created_at: Mapped[str] = mapped_column(String(64), index=True)


class SalesExternalLinkRow(Base):
    __tablename__ = "sales_external_links"
    __table_args__ = (
        Index("idx_sales_external_links_deal_sync", "deal_id", "last_sync_at"),
        Index("idx_sales_external_links_thread", "external_thread_id"),
        Index("idx_sales_external_links_voice_session", "voice_session_id"),
        Index("idx_sales_external_links_external_call", "external_call_id"),
        Index("idx_sales_external_links_interaction", "interaction_id"),
        Index("idx_sales_external_links_customer_phone", "customer_id", "phone_number"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    link_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(64), index=True)
    deal_id: Mapped[str] = mapped_column(String(64), index=True)
    communication_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    sales_call_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    channel_provider: Mapped[str] = mapped_column(String(32), index=True)
    external_thread_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    external_chat_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    external_call_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    voice_session_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
    ai_session_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
    interaction_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
    customer_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
    phone_number: Mapped[str | None] = mapped_column(String(64), nullable=True)
    external_status: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
    link_metadata_json: Mapped[str] = mapped_column(Text, default="{}")
    created_at: Mapped[str] = mapped_column(String(64), index=True)
    updated_at: Mapped[str] = mapped_column(String(64), index=True)
    last_sync_at: Mapped[str] = mapped_column(String(64), index=True)
