"use server";

import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { houseService } from "@/services/houses/house.service";
import {
  ValidationError,
  ConflictError,
  ForbiddenError,
  NotFoundError,
} from "@/services/errors";

export async function inviteUser(houseId: string, inviteeId: string) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return {
        success: false,
        error: "Vous devez être connecté",
      };
    }

    const invitation = await houseService.inviteUser({
      houseId,
      inviterId: session.user.id,
      inviteeId,
    });

    revalidatePath("/houses");
    revalidatePath(`/houses/${houseId}`);

    return {
      success: true,
      message: "Invitation envoyée",
      data: invitation,
    };
  } catch (error) {
    console.error("Invite user error:", error);

    if (
      error instanceof ValidationError ||
      error instanceof ConflictError ||
      error instanceof ForbiddenError
    ) {
      return { success: false, error: error.message };
    }

    return {
      success: false,
      error: "Une erreur est survenue lors de l'envoi de l'invitation",
    };
  }
}

export async function acceptInvitation(invitationId: string) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return {
        success: false,
        error: "Vous devez être connecté",
      };
    }

    const membership = await houseService.acceptInvitation(
      invitationId,
      session.user.id
    );

    revalidatePath("/houses");
    revalidatePath("/profile");
    revalidatePath("/invitations");

    return {
      success: true,
      message: "Invitation acceptée",
      data: membership,
    };
  } catch (error) {
    console.error("Accept invitation error:", error);

    if (
      error instanceof ValidationError ||
      error instanceof ConflictError ||
      error instanceof ForbiddenError ||
      error instanceof NotFoundError
    ) {
      return { success: false, error: error.message };
    }

    return {
      success: false,
      error: "Une erreur est survenue lors de l'acceptation de l'invitation",
    };
  }
}

export async function rejectInvitation(invitationId: string) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return {
        success: false,
        error: "Vous devez être connecté",
      };
    }

    await houseService.rejectInvitation(invitationId, session.user.id);

    revalidatePath("/houses");
    revalidatePath("/invitations");

    return { success: true, message: "Invitation refusée" };
  } catch (error) {
    console.error("Reject invitation error:", error);

    if (
      error instanceof ConflictError ||
      error instanceof ForbiddenError ||
      error instanceof NotFoundError
    ) {
      return { success: false, error: error.message };
    }

    return {
      success: false,
      error: "Une erreur est survenue lors du refus de l'invitation",
    };
  }
}

export async function cancelInvitation(invitationId: string) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return {
        success: false,
        error: "Vous devez être connecté",
      };
    }

    // Récupérer l'invitation pour obtenir le houseId avant de l'annuler
    const invitation = await houseService.getInvitationById(invitationId);

    await houseService.cancelInvitation(invitationId, session.user.id);

    revalidatePath("/houses");
    if (invitation?.houseId) {
      revalidatePath(`/houses/${invitation.houseId}`);
    }

    return { success: true, message: "Invitation annulée" };
  } catch (error) {
    console.error("Cancel invitation error:", error);

    if (
      error instanceof ConflictError ||
      error instanceof ForbiddenError ||
      error instanceof NotFoundError
    ) {
      return { success: false, error: error.message };
    }

    return {
      success: false,
      error: "Une erreur est survenue lors de l'annulation de l'invitation",
    };
  }
}
