import { db } from '../client';
import { projects, type Project, type NewProject } from '@banatie/database';
import { eq, and } from 'drizzle-orm';

export async function getProjectByName(
  organizationId: string,
  name: string,
): Promise<Project | null> {
  const [project] = await db
    .select()
    .from(projects)
    .where(and(eq(projects.organizationId, organizationId), eq(projects.name, name)))
    .limit(1);

  return project || null;
}

export async function createProject(data: NewProject): Promise<Project> {
  const [project] = await db.insert(projects).values(data).returning();

  return project!;
}

export async function listProjectsByOrganization(organizationId: string): Promise<Project[]> {
  return db
    .select()
    .from(projects)
    .where(eq(projects.organizationId, organizationId))
    .orderBy(projects.createdAt);
}
