/**
 * Real Estate Viewing Service
 * Manages property viewings - creation, rescheduling, cancellation.
 */

import { prisma } from "@/lib/db";
import { createId } from "@paralleldrive/cuid2";
import { logger } from "@/lib/logger";

interface CreateViewingInput {
  propertyId: string;
  brokerId?: string;
  clientName: string;
  clientPhone: string;
  clientEmail?: string;
  viewingDate: Date;
  viewingTime: string;
  source?: string;
}

export class ViewingService {
  static async createViewing(userId: string, input: CreateViewingInput) {
    const viewing = await prisma.viewing.create({
      data: {
        id: createId(),
        userId,
        propertyId: input.propertyId,
        brokerId: input.brokerId || null,
        clientName: input.clientName,
        clientPhone: input.clientPhone,
        clientEmail: input.clientEmail || null,
        viewingDate: input.viewingDate,
        viewingTime: input.viewingTime,
        status: "SCHEDULED",
        source: input.source || "manual",
      },
    });

    logger.info("Viewing created", {
      viewingId: viewing.id,
      propertyId: input.propertyId,
      userId,
    });

    return viewing;
  }

  static async rescheduleViewing(
    viewingId: string,
    userId: string,
    newDate: Date,
    newTime: string,
  ) {
    const viewing = await prisma.viewing.update({
      where: { id: viewingId },
      data: {
        viewingDate: newDate,
        viewingTime: newTime,
        status: "RESCHEDULED",
        updatedAt: new Date(),
      },
    });

    logger.info("Viewing rescheduled", {
      viewingId,
      newDate: newDate.toISOString(),
      newTime,
    });

    return viewing;
  }

  static async cancelViewing(viewingId: string, userId: string) {
    const viewing = await prisma.viewing.update({
      where: { id: viewingId },
      data: {
        status: "CANCELLED",
        updatedAt: new Date(),
      },
    });

    logger.info("Viewing cancelled", { viewingId, userId });

    return viewing;
  }
}
