# frozen_string_literal: true

class MarketingPagesController < ApplicationController
  before_action :set_showcase, only: %i[homepage alternative]

  PRIMARY_SHOWCASED_PAGE_SLUGS = %w[
    emma-lawler
    kumar
    lindsaycrouse

    ivanachen
    aaron-cohn
    victoria-martinez-de-la-cruz
  ].freeze

  SECONDARY_SHOWCASED_PAGE_SLUGS = %w[
    kaley-wendorf
    mairin
    lily-wang

    david-hagan
    joedaft
    jj
  ].freeze

  TERTIARY_SHOWCASED_PAGE_SLUGS = %w[
    jopie
    matt-mayo
    sinan-ozdemir

    kkurian
    jhm
    jackohara
  ].freeze

  def homepage
    if Rails.configuration.solo_mode
      return redirect_to new_account_registration_path if Account.count.zero?

      @account = Account.first
      return render 'public_pages/show'
    end

    @email_address = EmailAddress.new
    redirect_to page_path(current_account.slug) if current_account
  end

  ALTERNATIVES = {
    'revue' => {
      title: 'Revue',
      description: 'Postcard is a Revue alternative built for dependability. It is a personal website and newsletter that you can host on your own domain.' # rubocop:disable Layout/LineLength
    }
  }.freeze

  def alternative
    @alternative = ALTERNATIVES[params[:slug]]
    raise ActiveRecord::RecordNotFound unless @alternative

    @page_title = @alternative[:title]
    @page_description = @alternative[:description]
    render "marketing_pages/alternative/#{params[:slug]}"
  end

  def sitemap
    # generated by rake task:
    # bundle exec rake sitemap:refresh:no_ping
    send_file('public/sitemaps/sitemap.xml')
  end

  private

  def set_showcase
    @featured_account = featured_account
    @primary_showcase_accounts = get_accounts(PRIMARY_SHOWCASED_PAGE_SLUGS, 'showcase-primary-v0')
    @secondary_showcase_accounts = get_accounts(SECONDARY_SHOWCASED_PAGE_SLUGS, 'showcase-secondary-v0')
    @tertiary_showcase_accounts = get_accounts(TERTIARY_SHOWCASED_PAGE_SLUGS, 'showcase-tertiary-v0')
  end

  def get_accounts(slugs, cache_key)
    count = slugs.count

    return Account.order(created_at: :desc).limit(count).all unless Rails.env.production?

    Rails.cache.fetch(cache_key, expires_in: 1.hour) do
      Account.where(slug: slugs.first(count)).to_a.sort_by do |a|
        slugs.index(a.slug) || 999
      end
    end
  end
end

def featured_account
  return Account.where(slug: 'philipithomas').includes(:pinned_post).first unless Rails.env.production?

  Rails.cache.fetch('homepage-featured-account', expires_in: 1.hour) do
    Account.where(slug: 'philipithomas').includes(:pinned_post).first
  end
end
