# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

module Gql::Types::Ticket
  class ArticleType < Gql::Types::BaseObject
    include Gql::Types::Concerns::HasDefaultModelFields
    include Gql::Types::Concerns::HasScopedModelUserRelations
    include Gql::Types::Concerns::HasInternalIdField
    include Gql::Types::Concerns::HasPunditAuthorization

    description 'Ticket articles'

    belongs_to :type, Gql::Types::Ticket::Article::TypeType
    belongs_to :sender, Gql::Types::Ticket::Article::SenderType

    field :subject, String

    field :author, Gql::Types::UserType, null: false, is_dependent_field: true, description: 'The originator (originBy, if any) or the creator of an article.'

    field :from, Gql::Types::AddressesFieldType
    field :to, Gql::Types::AddressesFieldType
    field :cc, Gql::Types::AddressesFieldType
    field :reply_to, Gql::Types::AddressesFieldType
    field :message_id, String
    field :message_id_md5, String
    field :in_reply_to, String
    field :content_type, String, null: false
    field :body, String, null: false, description: 'Raw body as saved in the database.'
    field :body_with_urls, String, null: false, description: 'Body with cid: URLs replaced for inline images in HTML articles.'
    field :body_rendering_error, Boolean, null: false, description: 'True when the body could not be rendered due to HTML processing issues and contains an untranslated error message.'
    field :body_excerpt, String, description: 'Short plain-text excerpt of the body (~50 words, cut on sentence boundaries).'
    field :internal, Boolean, null: false

    field :preferences, ::GraphQL::Types::JSON
    field :security_state, Gql::Types::Ticket::Article::SecurityStateType
    field :media_error_state, Gql::Types::Ticket::Article::MediaErrorStateType

    field :attachments, [Gql::Types::StoredFileType, { null: false }], null: false, description: 'All attached files as stored in the database.'
    field :attachments_without_inline, [Gql::Types::StoredFileType, { null: false }], null: false, description: 'Attachments for display, with inline images filtered out.'

    scoped_fields do
      field :time_unit, Float, description: 'The accounted time of this article.'
      field :accounted_time_type, Gql::Types::Ticket::TimeAccounting::TypeType, description: 'The activity type of the accounted time of this article.'
    end

    internal_fields do
      field :highlighted_texts, [Gql::Types::Ticket::Article::HighlightedTextType]
      field :detected_language, String

      # Translating is an agent action, so is knowing about translations.
      field :translation_available, Boolean, description: 'Whether a translation into the given locale is stored for the current content of this article' do
        argument :target_locale, String, required: false, description: 'The locale to translate into, e.g. "de-de".'
      end

      field :translation, Gql::Types::ContentTranslationType, null: true, description: 'The stored translation of the current article content' do
        argument :target_locale, String, description: 'The locale to translate into, e.g. "de-de".'
      end
    end

    belongs_to :ticket, Gql::Types::TicketType, null: false
    # belongs_to :origin_by, Gql::Types::UserType # see :author instead

    def body_with_urls
      display_article[:body]
    end

    def body_rendering_error
      @object.body_rendering_error
    end

    def attachments_without_inline
      display_article[:attachments]
    end

    def security_state
      @object.preferences['security']
    end

    def media_error_state
      @object.preferences&.dig('whatsapp')
    end

    def highlighted_texts
      @object.preferences&.dig('highlight')&.split('|')&.drop(1) || []
    end

    def time_unit
      time_accounting.then { |elem| elem&.time_unit }
    end

    def accounted_time_type
      time_accounting.then do |elem|
        next if elem&.type_id.blank?

        Gql::RecordLoader.for(::Ticket::TimeAccounting::Type).load(elem.type_id)
      end
    end

    # Both batched per page and locale; without a locale there is nothing to look up.
    def translation_available(target_locale: nil)
      return if target_locale.blank?

      load_translation(target_locale, with_content: context[:article_translation_content_locale] == target_locale).then(&:present?)
    end

    def translation(target_locale:)
      return if !Setting.get('content_translation_service') || !Setting.get('content_translation_ticket_article')
      return if !Pundit.policy!(context.current_user, @object).agent_read_access?

      load_translation(target_locale, with_content: true)
    end

    private

    def load_translation(target_locale, with_content:)
      (context[:article_translations] || {}).fetch([@object.id, target_locale]) do
        Gql::Loaders::Ticket::ArticleTranslationLoader.for(target_locale, with_content:).load(@object)
      end
    end

    # Batched, so listing many articles of the same ticket does not cause one query per article.
    def time_accounting
      Gql::RecordLoader
        .for(::Ticket::TimeAccounting, column: :ticket_article_id)
        .load(@object.id)
    end

    def display_article
      @display_article ||= begin
        body, attachments = @object.class.insert_urls(@object)

        { body:, attachments: }
      end
    end
  end
end
