'use server';

import { getOrganizationByEmail, createOrganization } from '../db/queries/organizations';
import { getProjectByName, createProject } from '../db/queries/projects';
import type { Organization, Project } from '@banatie/database';

export async function getOrCreateOrganization(email: string, name: string): Promise<Organization> {
  // Try to find existing organization
  const existing = await getOrganizationByEmail(email);
  if (existing) {
    return existing;
  }

  // Create new organization
  return createOrganization({ email, name });
}

export async function getOrCreateProject(organizationId: string, name: string): Promise<Project> {
  // Try to find existing project
  const existing = await getProjectByName(organizationId, name);
  if (existing) {
    return existing;
  }

  // Create new project
  return createProject({ organizationId, name });
}

export async function getOrCreateOrgAndProject(
  email: string,
  orgName: string,
  projectName: string,
): Promise<{ organization: Organization; project: Project }> {
  // Get or create organization
  const organization = await getOrCreateOrganization(email, orgName);

  // Get or create project
  const project = await getOrCreateProject(organization.id, projectName);

  return { organization, project };
}
