"use server";

import { revalidatePath } from "next/cache";

import { BUCKETS, DATABASE_ID, TABLES } from "./schema";
import { createAdminClient } from "./server";
import { requireTenant } from "./tenant-guard";

type DeleteResult = { ok: boolean; error?: string };

export async function deletePropertyImageAction(fileId: string): Promise<DeleteResult> {
  await requireTenant();
  const { storage } = createAdminClient();

  try {
    await storage.deleteFile(BUCKETS.propertyImages, fileId);
    return { ok: true };
  } catch {
    return { ok: false, error: "Fotoğraf silinemedi." };
  }
}

// Storage'dan siler VE property kaydındaki imageIds listesini günceller.
// PropertyImageSheet'ten çağrılır — ayrıca "Kaydet"e basma gerekmez.
export async function deletePropertyImageAndSyncAction(
  propertyId: string,
  fileId: string,
  remainingIds: string[],
): Promise<DeleteResult> {
  await requireTenant();
  const { storage, tablesDB } = createAdminClient();

  try {
    await storage.deleteFile(BUCKETS.propertyImages, fileId);
  } catch {
    return { ok: false, error: "Fotoğraf silinemedi." };
  }

  try {
    await tablesDB.updateRow(DATABASE_ID, TABLES.properties, propertyId, {
      imageIds: JSON.stringify(remainingIds),
    });
  } catch {
    return { ok: false, error: "Fotoğraf silindi ancak ilan kaydı güncellenemedi." };
  }

  revalidatePath(`/properties/${propertyId}`);
  revalidatePath("/properties");
  return { ok: true };
}
