class ProjectsController < ApplicationController
  include ApplicationHelper
  before_action :require_login, except: %i[index branches group_type_list]
  before_action :find_project, only: %i[branches]

  def index
    scope = Projects::ListQuery.call(params)
    @total_count = scope.size
    @projects = paginate(scope)
  end

  def create
    ActiveRecord::Base.transaction do
      Projects::CreateForm.new(project_params).validate!
      @project = Projects::CreateService.new(current_user, project_params).call
    end
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  def migrate
    ActiveRecord::Base.transaction do
      Projects::MigrateForm.new(mirror_params).validate!
      @project = Projects::MigrateService.new(current_user, mirror_params).call
    end
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  def branches
    @branches = Gitea::Repository::BranchesService.new(@project.owner, @project.identifier).call
  end

  def group_type_list
    @project_group_list = Project.visible.group(:project_type).select('project_type, count(*) AS projects_count')
  end

  private
  def find_project
    @project = Project.find_by_identifier! params[:id]
  end

  def project_params
    params.permit(:user_id, :name, :description, :repository_name,
      :project_category_id, :project_language_id, :license_id, :ignore_id)
  end

  def mirror_params
    params.permit(:user_id, :name, :description, :repository_name,
      :project_category_id, :project_language_id, :clone_addr, :private)
  end
end