class NicoTagsController < ApplicationController
  def index
    limit = (params[:limit] || 20).to_i
    cursor = params[:cursor].presence

    q = Tag.nico_tags.includes(:linked_tags).order(updated_at: :desc)
    q = q.where('tags.updated_at < ?', Time.iso8601(cursor)) if cursor

    tags = q.limit(limit + 1)

    next_cursor = nil
    if tags.size > limit
      next_cursor = tags.last.updated_at.iso8601(6)
      tags = tags.first(limit)
    end

    render json: { tags: tags.map { |tag|
      tag.as_json(include: :linked_tags)
    }, next_cursor: }
  end

  def update
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.member?

    id = params[:id].to_i

    tag = Tag.find(id)
    return head :bad_request if tag.category != 'nico'

    linked_tag_names = params[:tags].to_s.split(' ')
    linked_tags = Tag.normalise_tags(linked_tag_names, with_tagme: false)
    return head :bad_request if linked_tags.filter { |t| t.category == 'nico' }.present?

    tag.linked_tags = linked_tags
    tag.updated_at = Time.now
    tag.save!

    render json: tag.linked_tags, status: :ok
  end
end
