import { getOrderUpdateForDeliveryInvitationAction, } from "../_shared/delivery-invitations.ts"; import { createServiceClient } from "../_shared/chatbot.ts"; import { insertIntegrationEvent } from "../_shared/integration-events.ts"; const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type", }; Deno.serve(async (request) => { if (request.method === "OPTIONS") { return new Response("ok", { headers: corsHeaders }); } if (request.method !== "POST") { return new Response(JSON.stringify({ error: "Method not allowed" }), { status: 405, headers: { ...corsHeaders, "Content-Type": "application/json", }, }); } try { const body = (await request.json()) as { orderId?: string; reason?: string; note?: string; targetStatus?: "Передан логисту" | "Платное хранение"; }; if (!body.orderId) { return new Response(JSON.stringify({ error: "orderId is required" }), { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json", }, }); } const supabase = createServiceClient(); const { data: currentOrder, error: orderError } = await supabase .from("orders") .select("id, status, delivery_agreement_status") .eq("id", body.orderId) .single(); if (orderError) { throw orderError; } const targetStatus = body.targetStatus || "Передан логисту"; const action = targetStatus === "Платное хранение" ? "mark_paid_storage" : "transfer_to_logistics"; const orderUpdate = getOrderUpdateForDeliveryInvitationAction(action); const { error: invitationError } = await supabase .from("delivery_invitations") .update({ state: targetStatus === "Платное хранение" ? "paid_storage" : "transferred_to_logistics", ...(targetStatus === "Платное хранение" ? { paid_storage_at: new Date().toISOString() } : { logistics_transferred_at: new Date().toISOString() }), }) .eq("order_id", body.orderId); if (invitationError) { throw invitationError; } const { error: updateError } = await supabase .from("orders") .update({ status: orderUpdate?.status, delivery_agreement_status: body.note || orderUpdate?.deliveryAgreementStatus, }) .eq("id", body.orderId); if (updateError) { throw updateError; } const { error: historyError } = await supabase.from("order_history").insert({ order_id: body.orderId, action: targetStatus === "Платное хранение" ? "Перевод на платное хранение" : "Передача заказа логисту", old_status: currentOrder.status, new_status: orderUpdate?.status, metadata: { old_delivery_agreement_status: currentOrder.delivery_agreement_status, new_delivery_agreement_status: body.note || orderUpdate?.deliveryAgreementStatus, reason: body.reason || null, target_status: targetStatus, }, }); if (historyError) { throw historyError; } await insertIntegrationEvent(supabase, { order_id: body.orderId, event_type: targetStatus === "Платное хранение" ? "delivery_paid_storage_requested" : "delivery_transfer_to_logistics", direction: "internal", status: "success", payload: { reason: body.reason || null, note: body.note || null, target_status: targetStatus, }, }); return new Response( JSON.stringify({ ok: true, orderId: body.orderId, status: orderUpdate?.status, deliveryAgreementStatus: body.note || orderUpdate?.deliveryAgreementStatus, }), { headers: { ...corsHeaders, "Content-Type": "application/json", }, }, ); } catch (error) { return new Response( JSON.stringify({ ok: false, error: error instanceof Error ? error.message : "Unexpected error", }), { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json", }, }, ); } });