import { BadRequestError, NotFoundError, ForbiddenError } from "../../common/errors/http-errors";
import * as orgRepo from "./organization.repo";

export async function createOrganization(userId: string, data: any) {
  const user = await orgRepo.findUserWithOrg(userId);
  if (!user) throw new BadRequestError("User not found");
  if (user.organizationId) throw new BadRequestError("User already has an organization");
  return orgRepo.createOrganizationTx(userId, data);
}

export async function updateOrganization(userId: string, data: any) {
  const user = await orgRepo.findUserWithOrg(userId);
  if (!user) throw new BadRequestError("User not found");
  if (!user.organizationId) throw new NotFoundError("Organization not found");
  return orgRepo.updateOrganizationById(user.organizationId, data);
}

export async function getOrganization(userId: string) {
  const user = await orgRepo.findUserWithOrg(userId);
  if (!user) throw new BadRequestError("User not found");
  if (!user.organizationId) throw new NotFoundError("Organization not found");
  const org = await orgRepo.findOrganizationById(user.organizationId);
  if (!org) throw new NotFoundError("Organization not found");
  return org;
}

export async function getAllOrganizations(userId: string) {
  const user = await orgRepo.findUserWithOrg(userId);
  if (!user) throw new BadRequestError("User not found");
  if (user.role !== "SUPER_ADMIN") throw new ForbiddenError("Only super admin can access all organizations");
  return orgRepo.findAllOrganizations();
}

export async function deleteOrganization(userId: string, organizationId: string) {
  const user = await orgRepo.findUserWithOrg(userId);
  if (!user) throw new BadRequestError("User not found");
  if (user.role !== "SUPER_ADMIN") throw new ForbiddenError("Only super admin can delete organizations");
  const org = await orgRepo.findOrganizationById(organizationId);
  if (!org) throw new NotFoundError("Organization not found");
  return orgRepo.deleteOrganizationTx(organizationId);
}
