import { randomUUID } from 'crypto'
import { Organization } from '../types'
import { mongodb } from './mongodb'

const collection = mongodb.collection<Organization>('organizations')

export const createOrganization = async (
    organization: Pick<Organization, 'identity' | 'name' | 'members'>,
): Promise<Organization> => {
    const model: Organization = {
        ...organization,
        accessKey: 'key:' + randomUUID(),
        createdAt: new Date(),
    }
    await collection.insertOne(model)
    return model
}

export const getOrganization = async (identity: string): Promise<Organization> => {
    const organization = await collection.findOne({ identity })
    if (!organization) {
        throw new Error('Organization not found')
    }
    return organization
}

export const getOrganizationsByMember = async (member: string): Promise<Organization[]> => {
    return await collection
        .find({
            members: member,
        })
        .toArray()
}
