import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { db, profilesTable, type Profile } from "@workspace/db";

type ProfileInsert = typeof profilesTable.$inferInsert;

/**
 * Insert a profile with a collision-safe, monotonic profileId (`MDL-XXXX`)
 * derived from the row's own serial id. Using the serial id (rather than a
 * row count) guarantees uniqueness even under concurrent inserts and after
 * deletions. Wrapped in a transaction so the placeholder is never observable.
 */
export async function insertProfileWithGeneratedId(
  values: Omit<ProfileInsert, "profileId">,
): Promise<Profile> {
  return db.transaction(async (tx) => {
    const [row] = await tx
      .insert(profilesTable)
      .values({ ...values, profileId: `TMP-${randomUUID()}` })
      .returning();
    const profileId = `MDL-${String(row.id).padStart(4, "0")}`;
    const [updated] = await tx
      .update(profilesTable)
      .set({ profileId })
      .where(eq(profilesTable.id, row.id))
      .returning();
    return updated;
  });
}

export function serializeProfile(p: Profile) {
  return {
    id: p.id,
    profileId: p.profileId,
    userId: p.userId,
    name: p.name,
    city: p.city,
    photoUrl: p.photoUrl,
    bio: p.bio,
    proStatus: p.proStatus,
    price1h: p.price1h,
    price2h: p.price2h,
    priceFullDay: p.priceFullDay,
    priceNight: p.priceNight,
    services: p.services,
    contactPlatform: p.contactPlatform,
    whatsappNumber: p.whatsappNumber,
    approvalStatus: p.approvalStatus,
    isFeatured: p.isFeatured,
    isActive: p.isActive,
    tags: p.tags,
    createdAt: p.createdAt,
  };
}
