import { gql } from "graphql-tag";

export const typeDefs = gql`
  scalar DateTime

  type Query {
    me: User
    organization(id: ID!): Organization

    # Поиск организаций по типу для добавления в контрагенты
    searchOrganizations(
      type: OrganizationType
      search: String
    ): [Organization!]!

    # Мои контрагенты
    myCounterparties: [Organization!]!

    # Поставщики поставок
    supplySuppliers: [SupplySupplier!]!

    # Логистика организации
    organizationLogistics(organizationId: ID!): [Logistics!]!

    # Входящие заявки
    incomingRequests: [CounterpartyRequest!]!

    # Исходящие заявки
    outgoingRequests: [CounterpartyRequest!]!

    # Сообщения с контрагентом
    messages(counterpartyId: ID!, limit: Int, offset: Int): [Message!]!

    # Список чатов (последние сообщения с каждым контрагентом)
    conversations: [Conversation!]!

    # Услуги организации
    myServices: [Service!]!

    # Расходники организации
    mySupplies: [Supply!]!

    # Заказы поставок расходников
    supplyOrders: [SupplyOrder!]!

    # Логистика организации
    myLogistics: [Logistics!]!

    # Поставки Wildberries
    myWildberriesSupplies: [WildberriesSupply!]!

    # Товары оптовика
    myProducts: [Product!]!

    # Все товары всех оптовиков для маркета
    allProducts(search: String, category: String): [Product!]!

    # Все категории
    categories: [Category!]!

    # Корзина пользователя
    myCart: Cart

    # Избранные товары пользователя
    myFavorites: [Product!]!

    # Сотрудники организации
    myEmployees: [Employee!]!
    employee(id: ID!): Employee

    # Табель сотрудника за месяц
    employeeSchedule(
      employeeId: ID!
      year: Int!
      month: Int!
    ): [EmployeeSchedule!]!

    # Публичные услуги контрагента (для фулфилмента)
    counterpartyServices(organizationId: ID!): [Service!]!

    # Публичные расходники контрагента (для оптовиков)
    counterpartySupplies(organizationId: ID!): [Supply!]!

    # Админ запросы
    adminMe: Admin
    allUsers(search: String, limit: Int, offset: Int): UsersResponse!

    # Wildberries статистика
    getWildberriesStatistics(
      period: String
      startDate: String
      endDate: String
    ): WildberriesStatisticsResponse!

    # Отладка рекламы (временно)
    debugWildberriesAdverts: DebugAdvertsResponse!

    # Статистика кампаний Wildberries
    getWildberriesCampaignStats(
      input: WildberriesCampaignStatsInput!
    ): WildberriesCampaignStatsResponse!
  }

  type Mutation {
    # Авторизация через SMS
    sendSmsCode(phone: String!): SmsResponse!
    verifySmsCode(phone: String!, code: String!): AuthResponse!

    # Валидация ИНН
    verifyInn(inn: String!): InnValidationResponse!

    # Обновление профиля пользователя
    updateUserProfile(
      input: UpdateUserProfileInput!
    ): UpdateUserProfileResponse!

    # Обновление данных организации по ИНН
    updateOrganizationByInn(inn: String!): UpdateOrganizationResponse!

    # Регистрация организации
    registerFulfillmentOrganization(
      input: FulfillmentRegistrationInput!
    ): AuthResponse!
    registerSellerOrganization(input: SellerRegistrationInput!): AuthResponse!

    # Работа с API ключами
    addMarketplaceApiKey(input: MarketplaceApiKeyInput!): ApiKeyResponse!
    removeMarketplaceApiKey(marketplace: MarketplaceType!): Boolean!

    # Выход из системы
    logout: Boolean!

    # Работа с контрагентами
    sendCounterpartyRequest(
      organizationId: ID!
      message: String
    ): CounterpartyRequestResponse!
    respondToCounterpartyRequest(
      requestId: ID!
      accept: Boolean!
    ): CounterpartyRequestResponse!
    cancelCounterpartyRequest(requestId: ID!): Boolean!
    removeCounterparty(organizationId: ID!): Boolean!

    # Работа с сообщениями
    sendMessage(
      receiverOrganizationId: ID!
      content: String
      type: MessageType = TEXT
    ): MessageResponse!
    sendVoiceMessage(
      receiverOrganizationId: ID!
      voiceUrl: String!
      voiceDuration: Int!
    ): MessageResponse!
    sendImageMessage(
      receiverOrganizationId: ID!
      fileUrl: String!
      fileName: String!
      fileSize: Int!
      fileType: String!
    ): MessageResponse!
    sendFileMessage(
      receiverOrganizationId: ID!
      fileUrl: String!
      fileName: String!
      fileSize: Int!
      fileType: String!
    ): MessageResponse!
    markMessagesAsRead(conversationId: ID!): Boolean!

    # Работа с услугами
    createService(input: ServiceInput!): ServiceResponse!
    updateService(id: ID!, input: ServiceInput!): ServiceResponse!
    deleteService(id: ID!): Boolean!

    # Работа с расходниками
    createSupply(input: SupplyInput!): SupplyResponse!
    updateSupply(id: ID!, input: SupplyInput!): SupplyResponse!
    deleteSupply(id: ID!): Boolean!

    # Заказы поставок расходников
    createSupplyOrder(input: SupplyOrderInput!): SupplyOrderResponse!
    updateSupplyOrderStatus(id: ID!, status: SupplyOrderStatus!): SupplyOrderResponse!

    # Работа с логистикой
    createLogistics(input: LogisticsInput!): LogisticsResponse!
    updateLogistics(id: ID!, input: LogisticsInput!): LogisticsResponse!
    deleteLogistics(id: ID!): Boolean!

    # Работа с товарами (для оптовиков)
    createProduct(input: ProductInput!): ProductResponse!
    updateProduct(id: ID!, input: ProductInput!): ProductResponse!
    deleteProduct(id: ID!): Boolean!

    # Работа с категориями
    createCategory(input: CategoryInput!): CategoryResponse!
    updateCategory(id: ID!, input: CategoryInput!): CategoryResponse!
    deleteCategory(id: ID!): Boolean!

    # Работа с корзиной
    addToCart(productId: ID!, quantity: Int = 1): CartResponse!
    updateCartItem(productId: ID!, quantity: Int!): CartResponse!
    removeFromCart(productId: ID!): CartResponse!
    clearCart: Boolean!

    # Работа с избранным
    addToFavorites(productId: ID!): FavoritesResponse!
    removeFromFavorites(productId: ID!): FavoritesResponse!

    # Работа с сотрудниками
    createEmployee(input: CreateEmployeeInput!): EmployeeResponse!
    updateEmployee(id: ID!, input: UpdateEmployeeInput!): EmployeeResponse!
    deleteEmployee(id: ID!): Boolean!
    updateEmployeeSchedule(input: UpdateScheduleInput!): Boolean!

    # Работа с поставками Wildberries
    createWildberriesSupply(
      input: CreateWildberriesSupplyInput!
    ): WildberriesSupplyResponse!
    updateWildberriesSupply(
      id: ID!
      input: UpdateWildberriesSupplyInput!
    ): WildberriesSupplyResponse!
    deleteWildberriesSupply(id: ID!): Boolean!

    # Работа с поставщиками для поставок
    createSupplySupplier(
      input: CreateSupplySupplierInput!
    ): SupplySupplierResponse!

    # Админ мутации
    adminLogin(username: String!, password: String!): AdminAuthResponse!
    adminLogout: Boolean!
  }

  # Типы данных
  type User {
    id: ID!
    phone: String!
    avatar: String
    managerName: String
    organization: Organization
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  type Organization {
    id: ID!
    inn: String!
    kpp: String
    name: String
    fullName: String
    address: String
    addressFull: String
    ogrn: String
    ogrnDate: DateTime
    type: OrganizationType!
    status: String
    actualityDate: DateTime
    registrationDate: DateTime
    liquidationDate: DateTime
    managementName: String
    managementPost: String
    opfCode: String
    opfFull: String
    opfShort: String
    okato: String
    oktmo: String
    okpo: String
    okved: String
    employeeCount: Int
    revenue: String
    taxSystem: String
    phones: JSON
    emails: JSON
    users: [User!]!
    apiKeys: [ApiKey!]!
    services: [Service!]!
    supplies: [Supply!]!
    isCounterparty: Boolean
    isCurrentUser: Boolean
    hasOutgoingRequest: Boolean
    hasIncomingRequest: Boolean
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  type ApiKey {
    id: ID!
    marketplace: MarketplaceType!
    apiKey: String!
    isActive: Boolean!
    validationData: JSON
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  # Входные типы для мутаций
  input UpdateUserProfileInput {
    # Аватар пользователя
    avatar: String

    # Контактные данные организации
    orgPhone: String
    managerName: String
    telegram: String
    whatsapp: String
    email: String

    # Банковские данные
    bankName: String
    bik: String
    accountNumber: String
    corrAccount: String
  }

  input FulfillmentRegistrationInput {
    phone: String!
    inn: String!
    type: OrganizationType!
  }

  input SellerRegistrationInput {
    phone: String!
    wbApiKey: String
    ozonApiKey: String
    ozonClientId: String
  }

  input MarketplaceApiKeyInput {
    marketplace: MarketplaceType!
    apiKey: String!
    clientId: String # Для Ozon
    validateOnly: Boolean # Только валидация без сохранения
  }

  # Ответные типы
  type SmsResponse {
    success: Boolean!
    message: String!
  }

  type AuthResponse {
    success: Boolean!
    message: String!
    token: String
    user: User
  }

  type InnValidationResponse {
    success: Boolean!
    message: String!
    organization: ValidatedOrganization
  }

  type ValidatedOrganization {
    name: String!
    fullName: String!
    address: String!
    isActive: Boolean!
  }

  type ApiKeyResponse {
    success: Boolean!
    message: String!
    apiKey: ApiKey
  }

  type UpdateUserProfileResponse {
    success: Boolean!
    message: String!
    user: User
  }

  type UpdateOrganizationResponse {
    success: Boolean!
    message: String!
    user: User
  }

  # Enums
  enum OrganizationType {
    FULFILLMENT
    SELLER
    LOGIST
    WHOLESALE
  }

  enum MarketplaceType {
    WILDBERRIES
    OZON
  }

  enum CounterpartyRequestStatus {
    PENDING
    ACCEPTED
    REJECTED
    CANCELLED
  }

  # Типы для контрагентов
  type CounterpartyRequest {
    id: ID!
    status: CounterpartyRequestStatus!
    message: String
    sender: Organization!
    receiver: Organization!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  type CounterpartyRequestResponse {
    success: Boolean!
    message: String!
    request: CounterpartyRequest
  }

  # Типы для сообщений
  type Message {
    id: ID!
    content: String
    type: MessageType
    voiceUrl: String
    voiceDuration: Int
    fileUrl: String
    fileName: String
    fileSize: Int
    fileType: String
    senderId: ID!
    senderOrganization: Organization!
    receiverOrganization: Organization!
    isRead: Boolean!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  enum MessageType {
    TEXT
    VOICE
    IMAGE
    FILE
  }

  type Conversation {
    id: ID!
    counterparty: Organization!
    lastMessage: Message
    unreadCount: Int!
    updatedAt: DateTime!
  }

  type MessageResponse {
    success: Boolean!
    message: String!
    messageData: Message
  }

  # Типы для услуг
  type Service {
    id: ID!
    name: String!
    description: String
    price: Float!
    imageUrl: String
    createdAt: DateTime!
    updatedAt: DateTime!
    organization: Organization!
  }

  input ServiceInput {
    name: String!
    description: String
    price: Float!
    imageUrl: String
  }

  type ServiceResponse {
    success: Boolean!
    message: String!
    service: Service
  }

  # Типы для расходников
  type Supply {
    id: ID!
    name: String!
    description: String
    price: Float!
    quantity: Int!
    unit: String
    category: String
    status: String
    date: DateTime!
    supplier: String
    minStock: Int
    currentStock: Int
    imageUrl: String
    createdAt: DateTime!
    updatedAt: DateTime!
    organization: Organization!
  }

  input SupplyInput {
    name: String!
    description: String
    price: Float!
    quantity: Int!
    unit: String!
    category: String!
    status: String!
    date: DateTime!
    supplier: String!
    minStock: Int!
    currentStock: Int!
    imageUrl: String
  }

  type SupplyResponse {
    success: Boolean!
    message: String!
    supply: Supply
  }

  # Типы для заказов поставок расходников
  type SupplyOrder {
    id: ID!
    organizationId: ID!
    partnerId: ID!
    partner: Organization!
    deliveryDate: DateTime!
    status: SupplyOrderStatus!
    totalAmount: Float!
    totalItems: Int!
    fulfillmentCenterId: ID
    fulfillmentCenter: Organization
    items: [SupplyOrderItem!]!
    createdAt: DateTime!
    updatedAt: DateTime!
    organization: Organization!
  }

  type SupplyOrderItem {
    id: ID!
    productId: ID!
    product: Product!
    quantity: Int!
    price: Float!
    totalPrice: Float!
  }

  enum SupplyOrderStatus {
    PENDING
    CONFIRMED
    IN_TRANSIT
    DELIVERED
    CANCELLED
  }

  input SupplyOrderInput {
    partnerId: ID!
    deliveryDate: DateTime!
    fulfillmentCenterId: ID # ID фулфилмент-центра для доставки
    logisticsPartnerId: ID # ID логистической компании
    items: [SupplyOrderItemInput!]!
    notes: String # Дополнительные заметки к заказу
  }

  input SupplyOrderItemInput {
    productId: ID!
    quantity: Int!
  }

  type SupplyOrderProcessInfo {
    role: String! # Роль организации в процессе (SELLER, FULFILLMENT, LOGIST)
    supplier: String! # Название поставщика
    fulfillmentCenter: ID # ID фулфилмент-центра
    logistics: ID # ID логистической компании
    status: String! # Текущий статус заказа
  }

  type SupplyOrderResponse {
    success: Boolean!
    message: String!
    order: SupplyOrder
    processInfo: SupplyOrderProcessInfo # Информация о процессе поставки
  }

  # Типы для логистики
  type Logistics {
    id: ID!
    fromLocation: String!
    toLocation: String!
    priceUnder1m3: Float!
    priceOver1m3: Float!
    description: String
    createdAt: DateTime!
    updatedAt: DateTime!
    organization: Organization!
  }

  input LogisticsInput {
    fromLocation: String!
    toLocation: String!
    priceUnder1m3: Float!
    priceOver1m3: Float!
    description: String
  }

  type LogisticsResponse {
    success: Boolean!
    message: String!
    logistics: Logistics
  }

  # Типы для категорий товаров
  type Category {
    id: ID!
    name: String!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  # Типы для товаров оптовика
  type Product {
    id: ID!
    name: String!
    article: String!
    description: String
    price: Float!
    quantity: Int!
    category: Category
    brand: String
    color: String
    size: String
    weight: Float
    dimensions: String
    material: String
    images: [String!]!
    mainImage: String
    isActive: Boolean!
    createdAt: DateTime!
    updatedAt: DateTime!
    organization: Organization!
  }

  input ProductInput {
    name: String!
    article: String!
    description: String
    price: Float!
    quantity: Int!
    categoryId: ID
    brand: String
    color: String
    size: String
    weight: Float
    dimensions: String
    material: String
    images: [String!]
    mainImage: String
    isActive: Boolean
  }

  type ProductResponse {
    success: Boolean!
    message: String!
    product: Product
  }

  input CategoryInput {
    name: String!
  }

  type CategoryResponse {
    success: Boolean!
    message: String!
    category: Category
  }

  # Типы для корзины
  type Cart {
    id: ID!
    items: [CartItem!]!
    totalPrice: Float!
    totalItems: Int!
    createdAt: DateTime!
    updatedAt: DateTime!
    organization: Organization!
  }

  type CartItem {
    id: ID!
    product: Product!
    quantity: Int!
    totalPrice: Float!
    isAvailable: Boolean!
    availableQuantity: Int!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  type CartResponse {
    success: Boolean!
    message: String!
    cart: Cart
  }

  # Типы для избранного
  type FavoritesResponse {
    success: Boolean!
    message: String!
    favorites: [Product!]
  }

  # Типы для сотрудников
  type Employee {
    id: ID!
    firstName: String!
    lastName: String!
    middleName: String
    birthDate: DateTime
    avatar: String
    passportPhoto: String
    passportSeries: String
    passportNumber: String
    passportIssued: String
    passportDate: DateTime
    address: String
    position: String!
    department: String
    hireDate: DateTime!
    salary: Float
    status: EmployeeStatus!
    phone: String!
    email: String
    telegram: String
    whatsapp: String
    emergencyContact: String
    emergencyPhone: String
    scheduleRecords: [EmployeeSchedule!]!
    organization: Organization!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  enum EmployeeStatus {
    ACTIVE
    VACATION
    SICK
    FIRED
  }

  type EmployeeSchedule {
    id: ID!
    date: DateTime!
    status: ScheduleStatus!
    hoursWorked: Float
    notes: String
    employee: Employee!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  enum ScheduleStatus {
    WORK
    WEEKEND
    VACATION
    SICK
    ABSENT
  }

  input CreateEmployeeInput {
    firstName: String!
    lastName: String!
    middleName: String
    birthDate: DateTime
    avatar: String
    passportPhoto: String
    passportSeries: String
    passportNumber: String
    passportIssued: String
    passportDate: DateTime
    address: String
    position: String!
    department: String
    hireDate: DateTime!
    salary: Float
    phone: String!
    email: String
    telegram: String
    whatsapp: String
    emergencyContact: String
    emergencyPhone: String
  }

  input UpdateEmployeeInput {
    firstName: String
    lastName: String
    middleName: String
    birthDate: DateTime
    avatar: String
    passportPhoto: String
    passportSeries: String
    passportNumber: String
    passportIssued: String
    passportDate: DateTime
    address: String
    position: String
    department: String
    hireDate: DateTime
    salary: Float
    status: EmployeeStatus
    phone: String
    email: String
    telegram: String
    whatsapp: String
    emergencyContact: String
    emergencyPhone: String
  }

  input UpdateScheduleInput {
    employeeId: ID!
    date: DateTime!
    status: ScheduleStatus!
    hoursWorked: Float
    notes: String
  }

  type EmployeeResponse {
    success: Boolean!
    message: String!
    employee: Employee
  }

  type EmployeesResponse {
    success: Boolean!
    message: String!
    employees: [Employee!]!
  }

  # JSON скаляр
  scalar JSON

  # Админ типы
  type Admin {
    id: ID!
    username: String!
    email: String
    isActive: Boolean!
    lastLogin: String
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  type AdminAuthResponse {
    success: Boolean!
    message: String!
    token: String
    admin: Admin
  }

  type UsersResponse {
    users: [User!]!
    total: Int!
    hasMore: Boolean!
  }

  # Типы для поставок Wildberries
  type WildberriesSupply {
    id: ID!
    deliveryDate: DateTime
    status: WildberriesSupplyStatus!
    totalAmount: Float!
    totalItems: Int!
    cards: [WildberriesSupplyCard!]!
    organization: Organization!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  type WildberriesSupplyCard {
    id: ID!
    nmId: String!
    vendorCode: String!
    title: String!
    brand: String
    price: Float!
    discountedPrice: Float
    quantity: Int!
    selectedQuantity: Int!
    selectedMarket: String
    selectedPlace: String
    sellerName: String
    sellerPhone: String
    deliveryDate: DateTime
    mediaFiles: [String!]!
    selectedServices: [String!]!
    createdAt: DateTime!
    updatedAt: DateTime!
  }

  enum WildberriesSupplyStatus {
    DRAFT
    CREATED
    IN_PROGRESS
    DELIVERED
    CANCELLED
  }

  input CreateWildberriesSupplyInput {
    deliveryDate: DateTime
    cards: [WildberriesSupplyCardInput!]!
  }

  input WildberriesSupplyCardInput {
    nmId: String!
    vendorCode: String!
    title: String!
    brand: String
    price: Float!
    discountedPrice: Float
    quantity: Int!
    selectedQuantity: Int!
    selectedMarket: String
    selectedPlace: String
    sellerName: String
    sellerPhone: String
    deliveryDate: DateTime
    mediaFiles: [String!]
    selectedServices: [String!]
  }

  input UpdateWildberriesSupplyInput {
    deliveryDate: DateTime
    status: WildberriesSupplyStatus
    cards: [WildberriesSupplyCardInput!]
  }

  type WildberriesSupplyResponse {
    success: Boolean!
    message: String!
    supply: WildberriesSupply
  }

  # Wildberries статистика
  type WildberriesStatistics {
    date: String!
    sales: Int!
    orders: Int!
    advertising: Float!
    refusals: Int!
    returns: Int!
    revenue: Float!
    buyoutPercentage: Float!
  }

  type WildberriesStatisticsResponse {
    success: Boolean!
    message: String
    data: [WildberriesStatistics!]!
  }

  type DebugAdvertsResponse {
    success: Boolean!
    message: String
    campaignsCount: Int!
    campaigns: [DebugCampaign!]
  }

  type DebugCampaign {
    id: Int!
    name: String!
    status: Int!
    type: Int!
  }

  # Типы для поставщиков поставок
  type SupplySupplier {
    id: ID!
    name: String!
    contactName: String!
    phone: String!
    market: String
    address: String
    place: String
    telegram: String
    createdAt: DateTime!
  }

  input CreateSupplySupplierInput {
    name: String!
    contactName: String!
    phone: String!
    market: String
    address: String
    place: String
    telegram: String
  }

  type SupplySupplierResponse {
    success: Boolean!
    message: String
    supplier: SupplySupplier
  }

  # Типы для статистики кампаний
  input WildberriesCampaignStatsInput {
    campaigns: [CampaignStatsRequest!]!
  }

  input CampaignStatsRequest {
    id: Int!
    dates: [String!]
    interval: CampaignStatsInterval
  }

  input CampaignStatsInterval {
    begin: String!
    end: String!
  }

  type WildberriesCampaignStatsResponse {
    success: Boolean!
    message: String
    data: [WildberriesCampaignStats!]!
  }

  type WildberriesCampaignStats {
    advertId: Int!
    views: Int!
    clicks: Int!
    ctr: Float!
    cpc: Float!
    sum: Float!
    atbs: Int!
    orders: Int!
    cr: Float!
    shks: Int!
    sum_price: Float!
    dates: [String!]!
    days: [WildberriesCampaignDayStats!]!
    boosterStats: [WildberriesCampaignDayStats!]!
  }

  type WildberriesCampaignDayStats {
    date: String!
    views: Int!
    clicks: Int!
    ctr: Float!
    cpc: Float!
    sum: Float!
    atbs: Int!
    orders: Int!
    cr: Float!
    shks: Int!
    sum_price: Float!
  }
`;
