import type {
  ProjectSessionSummary,
  ProjectSummary,
  WorkspaceSkillSummary
} from "@qjclaw/shared-types";
import type { ProjectStoreService } from "./project-store.js";

export const EMPTY_PROJECT_INVENTORY_MESSAGE = "Waiting for cloud project bundle sync.";

export interface ActiveProjectWorkspaceState {
  projects: ProjectSummary[];
  currentProject: ProjectSummary | null;
  sessions: ProjectSessionSummary[];
  skills: WorkspaceSkillSummary[];
}

export async function getActiveProjectOrNull(projectStore: ProjectStoreService): Promise<ProjectSummary | null> {
  const projects = await projectStore.listProjects();
  if (projects.length === 0) {
    return null;
  }
  return projectStore.getActiveProject();
}

export async function requireActiveProject(projectStore: ProjectStoreService): Promise<ProjectSummary> {
  const project = await getActiveProjectOrNull(projectStore);
  if (!project) {
    throw new Error(EMPTY_PROJECT_INVENTORY_MESSAGE);
  }
  return project;
}

export async function loadActiveProjectWorkspaceState(projectStore: ProjectStoreService): Promise<ActiveProjectWorkspaceState> {
  const projects = await projectStore.listProjects();
  if (projects.length === 0) {
    return {
      projects,
      currentProject: null,
      sessions: [],
      skills: []
    };
  }

  const currentProject = await projectStore.getActiveProject();
  const [sessions, skills] = await Promise.all([
    projectStore.listSessions(currentProject.id),
    projectStore.listProjectSkills(currentProject.id)
  ]);

  return {
    projects,
    currentProject,
    sessions,
    skills
  };
}

export async function listSessionsForActiveProject(projectStore: ProjectStoreService): Promise<ProjectSessionSummary[]> {
  const project = await getActiveProjectOrNull(projectStore);
  if (!project) {
    return [];
  }
  return projectStore.listSessions(project.id);
}

export async function createSessionForActiveProject(
  projectStore: ProjectStoreService,
  title?: string
): Promise<ProjectSessionSummary> {
  const project = await requireActiveProject(projectStore);
  return projectStore.createSession(title, project.id);
}
