defmodule Microwaveprop.ApplicationTest do
  use ExUnit.Case, async: false

  alias Microwaveprop.Application, as: App

  describe "build_timestamp/0" do
    setup do
      original_env = System.get_env("DEPLOY_TIMESTAMP")
      original_file = Application.get_env(:microwaveprop, :build_timestamp_file)

      tmp = Path.join(System.tmp_dir!(), "build_timestamp_#{System.unique_integer([:positive])}")

      on_exit(fn ->
        if original_env do
          System.put_env("DEPLOY_TIMESTAMP", original_env)
        else
          System.delete_env("DEPLOY_TIMESTAMP")
        end

        if original_file do
          Application.put_env(:microwaveprop, :build_timestamp_file, original_file)
        else
          Application.delete_env(:microwaveprop, :build_timestamp_file)
        end

        File.rm(tmp)
      end)

      System.delete_env("DEPLOY_TIMESTAMP")
      Application.put_env(:microwaveprop, :build_timestamp_file, tmp)

      {:ok, tmp: tmp}
    end

    test "returns a DateTime when no sources are present" do
      assert %DateTime{} = App.build_timestamp()
    end

    test "reads ISO8601 timestamp from the build-timestamp file", %{tmp: tmp} do
      File.write!(tmp, "2026-04-15T12:30:00Z\n")
      assert App.build_timestamp() == ~U[2026-04-15 12:30:00Z]
    end

    test "file takes precedence over DEPLOY_TIMESTAMP env", %{tmp: tmp} do
      File.write!(tmp, "2026-04-15T12:30:00Z")
      System.put_env("DEPLOY_TIMESTAMP", "2026-01-01T00:00:00Z")
      assert App.build_timestamp() == ~U[2026-04-15 12:30:00Z]
    end

    test "falls back to DEPLOY_TIMESTAMP env when file is absent" do
      System.put_env("DEPLOY_TIMESTAMP", "2026-02-02T02:02:02Z")
      assert App.build_timestamp() == ~U[2026-02-02 02:02:02Z]
    end

    test "falls back to compile time when both are malformed", %{tmp: tmp} do
      File.write!(tmp, "not-a-timestamp")
      System.put_env("DEPLOY_TIMESTAMP", "also-garbage")
      assert %DateTime{} = App.build_timestamp()
    end
  end
end
