class ImagesController < ApplicationController
  # Allow unauthenticated access to index and show actions
  # allow_unauthenticated_access only: [:index, :show, :search]

  before_action :set_image, only: [ :show, :edit, :update, :destroy, :approve, :reject ]
  before_action :set_tag, only: [ :index ], if: -> { params[:tag_id].present? }

  def index
    if params[:tag_id].present?
      # When accessed via /tags/:tag_id/images
      @q = @tag.images.includes(:user, :tags).ransack(params[:q])
      @images = @q.result(distinct: true).with_attached_file.order(created_at: :desc).page(params[:page]).per(12)

      render inertia: "tags/images/Index", props: {
        tag: @tag.as_json(only: [ :id, :name, :catalog ], methods: [ :images_count ]),
        images: @images.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ]),
        filters: params[:q] || {},
        pagination: {
          current_page: @images.current_page,
          total_pages: @images.total_pages,
          total_count: @images.total_count
        }
      }
    else
      # Regular /images index
      @q = Current.user.images.includes(:user, :tags).ransack(params[:q])
      @images = @q.result(distinct: true).with_attached_file.order(created_at: :desc).page(params[:page]).per(12)

      render inertia: "images/Index", props: {
        images: @images.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ]),
        filters: params[:q] || {},
        pagination: {
          current_page: @images.current_page,
          total_pages: @images.total_pages,
          total_count: @images.total_count
        }
      }
    end
  end

  def show
    render inertia: "images/Show", props: {
      image: @image.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ]),
      can_edit: Current.user == @image.user && @image.status == "pending",
      can_approve: Current.user&.admin?,
      can_delete: Current.user == @image.user && @image.status == "pending" || Current.user&.admin?
    }
  end

  def new
    @image = Image.new
    render inertia: "images/New", props: {}
  end

  def create
    @image = Current.user.images.new(image_params)

    if @image.save
      # 处理标签 - 从表单数据中获取tag_ids
      if params[:image] && params[:image][:tag_ids].present?
        @image.set_tags_by_ids(params[:image][:tag_ids])
      end
      redirect_to image_path(@image), notice: "Image was successfully uploaded and is pending review."
    else
      render inertia: "images/New", props: {
        image: @image.as_json(methods: [ :errors ]),
        errors: @image.errors
      }, status: :unprocessable_entity
    end
  end

  def edit
    authorize_user

    unless @image.status == "pending" || Current.user&.admin?
      return redirect_to image_path(@image), notice: "没有权限修改"
    end

    render inertia: "images/Edit", props: {
      image: @image.as_json(include: [ :tags ], methods: [ :file_url ])
    }
  end

  def update
    authorize_user

    unless @image.status == "pending" || Current.user&.admin?
      return redirect_to image_path(@image), notice: "没有权限修改"
    end

    if @image.update(image_params)
      # 处理标签 - 从表单数据中获取tag_ids
      if params[:image] && params[:image][:tag_ids].present?
        @image.set_tags_by_ids(params[:image][:tag_ids])
      end
      redirect_to image_path(@image), notice: "Image was successfully updated."
    else
      render inertia: "images/Edit", props: {
        image: @image.as_json(include: [ :tags ], methods: [ :file_url, :errors ]),
        errors: @image.errors
      }, status: :unprocessable_entity
    end
  end

  def destroy
    authorize_admin

    @image.destroy!
    redirect_to images_path, notice: "Image was successfully deleted."
  end

  def approve
    authorize_admin

    Image.transaction do
      @image.approved!
      @image.set_tags_by_ids(params[:tag_ids]) if params[:tag_ids].present?
    end

    redirect_to image_path(@image), notice: "Image was successfully approved."
  end

  def reject
    authorize_admin

    @image.rejected!
    redirect_to image_path(@image), notice: "Image was rejected."
  end

  private

  def set_image
    @image = Current.user.images.find(params[:id])
  end

  def set_tag
    @tag = Tag.find(params[:tag_id])
  end

  def image_params
    params.require(:image).permit(:title, :file, tag_ids: [])
  end

  def authorize_user
    unless Current.user == @image.user
      redirect_to images_path, alert: "You are not authorized to perform this action."
    end
  end

  def authorize_admin
    unless Current.user&.admin?
      redirect_to images_path, alert: "You are not authorized to perform this action."
    end
  end
end