import { createSupabaseServiceRoleClient } from "@/lib/supabase/service-role"; import { uploadRemoteImageToAliyunOss } from "@/server/storage/aliyun-oss"; type GalleryPhotoPickRow = { id: string; unsplash_id: string; urls: Record; }; function getMirrorSourceUrl(urls: Record) { const candidates = [ urls.full, urls.regular, urls.raw, urls.small, urls.thumb, ]; for (const candidate of candidates) { if (typeof candidate === "string" && candidate.length > 0) { return candidate; } } return null; } export async function updateGalleryPhotoPickStatus({ isPicked, pickedBy, unsplashId, }: { isPicked: boolean; pickedBy: string; unsplashId: string; }) { const supabase = createSupabaseServiceRoleClient(); const { data: photo, error: readError } = await supabase .from("wg_gallery_photos") .select("id,unsplash_id,urls") .eq("unsplash_id", unsplashId) .maybeSingle(); if (readError) { throw readError; } if (!photo) { throw new Error("Gallery photo was not found."); } const now = new Date().toISOString(); const update: Record = { is_picked: isPicked, picked_at: isPicked ? now : null, picked_by: isPicked ? pickedBy : null, oss_sync_error: null, }; if (isPicked) { const imageUrl = getMirrorSourceUrl(photo.urls); if (!imageUrl) { update.oss_sync_error = "No usable source image URL was found."; } else { const upload = await uploadRemoteImageToAliyunOss({ imageUrl, objectKeyPrefix: `gallery/unsplash/${photo.unsplash_id}`, }); if (upload.ok) { update.oss_bucket = upload.bucket; update.oss_object_key = upload.objectKey; update.oss_url = upload.url; update.oss_synced_at = now; } else { update.oss_sync_error = upload.error; } } } const { data, error } = await supabase .from("wg_gallery_photos") .update(update) .eq("unsplash_id", unsplashId) .select( "id,unsplash_id,slug,description,alt_description,width,height,color,color_family,likes,urls,user_info,photo_created_at,is_picked,picked_at,picked_by,oss_url,oss_object_key,oss_synced_at,oss_sync_error", ) .single(); if (error) { console.error("[gallery-pick] Supabase update failed", error); throw error; } return data; }