defmodule Todoit.Todo.Task do
  use Ash.Resource,
    otp_app: :todoit,
    domain: Todoit.Todo,
    data_layer: AshPostgres.DataLayer

  postgres do
    table "tasks"
    repo Todoit.Repo
  end

  actions do
    defaults [:create, :read, :update, :destroy]
    default_accept [:title, :description, :done]

    read :list_today do
      filter expr(inserted_at >= start_of_day(type(today(), :date)))
    end

    read :list_this_week do
      filter expr(inserted_at >= start_of_day(type(ago(7, :day), :date)))
    end
  end

  validations do
    validations do
      validate present([:title]) do
        message "You must provide a title"
      end
    end
  end

  attributes do
    uuid_primary_key :id

    attribute :title, :string do
      allow_nil? false
    end

    attribute :description, :string do
      default ""
    end

    attribute :done, :boolean do
      default false
    end

    create_timestamp :inserted_at
    update_timestamp :updated_at
  end

  calculations do
    calculate :display_title, :string, expr(title <> " (" <> description <> ")")

    calculate :is_overdue,
              :boolean,
              expr(not done and date_diff(^Date.utc_today(), inserted_at, :day) > 30)

    calculate :completion_status,
              :string,
              expr(
                if done do
                  "✓ Completed"
                else
                  "○ Pending"
                end
              )
  end
end
