defmodule Web.PostController do
  use Web, :controller

  def show(conn, %{"year" => year, "month" => month, "day" => day, "slug" => slug}) do
    with {year, ""} <- Integer.parse(year),
         {month, ""} <- Integer.parse(month),
         {day, ""} <- Integer.parse(day),
         {:ok, publish_date} <- Date.new(year, month, day) do
      post = Core.Posts.get_published_blog!(publish_date, slug)

      conn
      |> render_post(post)
    else
      _ -> raise Ecto.NoResultsError
    end
  end

  def show(conn, %{"status_id" => status_id}) do
    status = Core.Posts.get_published_status!(status_id)

    conn
    |> render_post(status)
  end

  def index(%{assigns: %{kind: kind}} = conn, _params) when kind in ~w[blog status]a do
    posts = Core.Posts.get_published_recent_posts(kind)

    render(conn, :index, posts: posts)
  end

  defp render_post(conn, %Schema.Post{kind: :blog} = blog) do
    render(conn, :show_blog, blog: blog)
  end

  defp render_post(conn, %Schema.Post{kind: :status} = status) do
    render(conn, :show_status, status: status)
  end
end