class MaterialVersionsController < ApplicationController
  def index
    page = (params[:page].presence || 1).to_i
    limit = (params[:limit].presence || 20).to_i

    page = 1 if page < 1
    limit = 1 if limit < 1

    offset = (page - 1) * limit

    q = MaterialVersion.includes(:created_by_user)
    q = q.where(material_id: params[:material_id]) if params[:material_id].present?
    q = q.where(tag_name: params[:tag].to_s.strip) if params[:tag].present?
    q = q.where(event_type: params[:event_type]) if params[:event_type].present?

    count = q.except(:order, :limit, :offset).count
    versions =
        q
        .order(Arel.sql('material_versions.created_at DESC, material_versions.id DESC'))
        .limit(limit)
        .offset(offset)

    render json: { versions: serialise_versions(versions), count: }
  end

  private

  def serialise_versions rows
    rows.map do |row|
      { id: row.id,
        material_id: row.material_id,
        version_no: row.version_no,
        event_type: row.event_type,
        tag_id: row.tag_id,
        tag_name: row.tag_name,
        tag_category: row.tag_category,
        url: row.url,
        source_kind: row.source_kind,
        source_uri: row.source_uri,
        source_path: row.source_path,
        source_file_id: row.source_file_id,
        normalized_source_key: row.normalized_source_key,
        file_blob_id: row.file_blob_id,
        file_filename: row.file_filename,
        file_content_type: row.file_content_type,
        file_byte_size: row.file_byte_size,
        file_sha256: row.file_sha256,
        export_paths_json: row.export_paths_hash,
        discarded_at: row.discarded_at,
        created_by_user: row.created_by_user&.as_json(UserRepr::BASE),
        created_at: row.created_at }
    end
  end
end
