import { db } from '../../index.js';
import { serializeLegacyInvite } from '../../serializers/invite.js';
import { serializeUser } from '../../serializers/user.js';
import { http } from '../../utils/openapi-http.js';
import { getSession } from '../../utils/session.js';

export default http.get('/api/v1/me/crate_owner_invitations', ({ response }) => {
  let { user } = getSession();
  if (!user) {
    return response('4XX').json({ errors: [{ detail: 'must be logged in to perform that action' }] }, { status: 403 });
  }

  let invites = db.crateOwnerInvitation.findMany(q => q.where(invite => invite.invitee.id === user.id));

  let inviters = invites.map(invite => invite.inviter);
  let invitees = invites.map(invite => invite.invitee);
  let users = [...new Set([...inviters, ...invitees])].toSorted((a, b) => a.id - b.id);

  return response(200).json({
    crate_owner_invitations: invites.map(invite => serializeLegacyInvite(invite)),
    users: users.map(user => serializeUser(user)),
  });
});
