"use server";

import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { tripService } from "@/server/services/trip.service";
import { paymentService } from "@/server/services/payment.service";
import { bookingService } from "@/server/services/booking.service";
import { revalidatePath } from "next/cache";

export async function markParticipantPaidAction(tripId: string) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return { error: "Kamu harus login terlebih dahulu" };
  }

  try {
    await tripService.markParticipantPayment(tripId, session.user.id);
    revalidatePath(`/trips/${tripId}`);
    revalidatePath("/trips");
    revalidatePath("/");
    revalidatePath("/profile");
    return { success: true };
  } catch (err) {
    return { error: (err as Error).message };
  }
}

export type StartMidtransResponse =
  | { error: string }
  | {
      success: true;
      snapToken: string;
      snapJsUrl: string;
      clientKey: string;
    };

/**
 * Mulai pembayaran online via Midtrans untuk trip tertentu. Resolve booking
 * dari (tripId, userId) supaya client tidak perlu tahu bookingId.
 */
export async function startMidtransPaymentAction(
  tripId: string
): Promise<StartMidtransResponse> {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return { error: "Kamu harus login terlebih dahulu" };
  }

  try {
    const booking = await bookingService.getByTripAndUser(
      tripId,
      session.user.id
    );
    if (!booking || booking.status === "CANCELLED") {
      return { error: "Kamu tidak terdaftar di trip ini" };
    }

    const result = await paymentService.startMidtransPayment(
      booking.id,
      session.user.id
    );
    return {
      success: true,
      snapToken: result.snapToken,
      snapJsUrl: result.snapJsUrl,
      clientKey: result.clientKey,
    };
  } catch (err) {
    return { error: (err as Error).message };
  }
}

export async function confirmParticipantPaymentAction(
  tripId: string,
  participantId: string
) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return { error: "Kamu harus login terlebih dahulu" };
  }

  try {
    await tripService.confirmParticipantPayment(
      tripId,
      participantId,
      session.user.id
    );
    revalidatePath(`/trips/${tripId}`);
    revalidatePath("/trips");
    revalidatePath("/");
    revalidatePath("/profile");
    return { success: true };
  } catch (err) {
    return { error: (err as Error).message };
  }
}
