package tests

import "core:fmt"
import "core:os"
import "core:testing"
import "../src/adapters"
import "../src/core"
import "../src/shared"

make_temp_project_path :: proc(t: ^testing.T) -> (string, string) {
	tmp_dir, err := os.make_directory_temp("", "comic-odin-*", context.temp_allocator)
	if err != nil {
		testing.expect(t, false, "failed to create temp directory")
		return "", ""
	}
	project_path := fmt.aprintf("%s/project.comic.json", tmp_dir)
	return tmp_dir, project_path
}

@test
storage_save_load_roundtrip :: proc(t: ^testing.T) {
	tmp_dir, project_path := make_temp_project_path(t)
	defer os.remove_all(tmp_dir)
	defer delete(project_path)

	state := core.new_initial_state()
	state.story_idea = "An inventor discovers a portal"
	state.story_genre = "scifi"
	state.user_mode = .Professional

	err := adapters.save_project(project_path, state)
	testing.expect(t, shared.is_ok(err), "save_project should succeed")

	loaded, lerr := adapters.load_project(project_path)
	defer core.dispose_state_owned(&loaded)
	testing.expect(t, shared.is_ok(lerr), "load_project should succeed")
	testing.expect(t, loaded.story_idea == state.story_idea, "story_idea should round-trip")
	testing.expect(t, loaded.story_genre == state.story_genre, "story_genre should round-trip")
	testing.expect(t, loaded.user_mode == state.user_mode, "user_mode should round-trip")
}

@test
storage_creates_asset_cache_dir :: proc(t: ^testing.T) {
	tmp_dir, project_path := make_temp_project_path(t)
	defer os.remove_all(tmp_dir)
	defer delete(project_path)

	state := core.new_initial_state()
	err := adapters.save_project(project_path, state)
	testing.expect(t, shared.is_ok(err), "save_project should succeed")

	asset_dir, derr := adapters.derive_asset_cache_dir(project_path)
	testing.expect(t, shared.is_ok(derr), "derive_asset_cache_dir should succeed")
	testing.expect(t, os.exists(asset_dir), "asset cache directory should exist")
	testing.expect(t, os.is_dir(asset_dir), "asset cache directory should be a directory")
}
