const { supabaseAdmin, supabaseServiceRole } = require('../config/supabase'); const { success, created, error, notFound, forbidden, serverError } = require('../utils/response'); const { notifyAdoptionResult, notifyNewApplication } = require('../services/notification.service'); // Client choice in this file: // supabaseAdmin — runs as the calling user, under RLS. Used for reads // and for writes to rows the caller owns. // supabaseServiceRole — bypasses RLS. Used only for the writes the adoption // state machine makes on someone else's rows (the // adopter touching the NGO's plant, the NGO creating the // adopter's garden row), after the ownership check in // code has passed. /** * POST /api/adoptions/:plantId/apply — submit adoption application */ async function apply(req, res) { try { const { plantId } = req.params; const { answers } = req.body; // Verify plant exists and is available const { data: plant } = await supabaseAdmin .from('plants') .select('id, ngo_id, plant_name, adoption_status') .eq('id', plantId) .maybeSingle(); if (!plant) return notFound(res, 'Plant not found'); if (plant.adoption_status !== 'available') { return error(res, 'This plant is no longer available for adoption', 400); } // Can't adopt own plant if (plant.ngo_id === req.user.id) { return error(res, 'You cannot adopt your own plant', 400); } // Check for existing application const { data: existing } = await supabaseAdmin .from('adoptions') .select('id') .eq('plant_id', plantId) .eq('adopter_id', req.user.id) .maybeSingle(); if (existing) { return error(res, 'You have already applied for this plant', 409, 'CONFLICT'); } // Create application const { data, error: dbError } = await supabaseAdmin .from('adoptions') .insert({ plant_id: plantId, adopter_id: req.user.id, ngo_id: plant.ngo_id, answers: answers || null, }) .select() .single(); if (dbError) { // Unique (plant_id, adopter_id): a concurrent duplicate submit if (dbError.code === '23505') { return error(res, 'You have already applied for this plant', 409, 'CONFLICT'); } return error(res, dbError.message, 400); } // Mark the plant as having a pending application. The plant belongs to the // NGO, so the adopter's own client cannot make this change. const { error: plantError } = await supabaseServiceRole .from('plants') .update({ adoption_status: 'pending' }) .eq('id', plantId) .eq('adoption_status', 'available'); if (plantError) { console.error('apply: failed to mark plant pending:', plantError); } // Notify NGO await notifyNewApplication({ ngoId: plant.ngo_id, adopterName: req.user.displayName || req.user.username, plantName: plant.plant_name, }); return created(res, data); } catch (err) { console.error('apply error:', err); return serverError(res); } } /** * GET /api/adoptions/my — adopter's applications */ async function myAdoptions(req, res) { try { const { data, error: dbError } = await supabaseAdmin .from('adoptions') .select(` *, plants!inner(plant_name, species, image_urls, location, address), profiles!adoptions_ngo_id_fkey(display_name, username) `) .eq('adopter_id', req.user.id) .order('created_at', { ascending: false }); if (dbError) return error(res, dbError.message, 400); return success(res, data); } catch (err) { console.error('myAdoptions error:', err); return serverError(res); } } /** * GET /api/adoptions/:id — single application detail */ async function getAdoption(req, res) { try { // Service role: the adopter's contact details are not readable through the // public profile columns. Access is decided by the check below. const { data, error: dbError } = await supabaseServiceRole .from('adoptions') .select(` *, plants!inner(plant_name, species, image_urls, location, address), profiles!adoptions_adopter_id_fkey(username, display_name, email, phone), profiles!adoptions_ngo_id_fkey(display_name, username) `) .eq('id', req.params.id) .maybeSingle(); if (dbError || !data) return notFound(res, 'Adoption application not found'); // Only the adopter or the NGO owner can view if (data.adopter_id !== req.user.id && data.ngo_id !== req.user.id && req.user.role !== 'admin') { return forbidden(res); } return success(res, data); } catch (err) { console.error('getAdoption error:', err); return serverError(res); } } /** * PATCH /api/adoptions/:id/approve — NGO approves adoption */ async function approve(req, res) { try { const { data: application } = await supabaseAdmin .from('adoptions') .select('*, plants!inner(plant_name, ngo_id)') .eq('id', req.params.id) .eq('status', 'pending') .maybeSingle(); if (!application) return notFound(res, 'Application not found or not pending'); if (application.ngo_id !== req.user.id) return forbidden(res, 'Only the plant owner can approve'); const now = new Date().toISOString(); // 1. Claim the plant. The status filter makes this the single point that // decides a race between two approvals: only one can match. const { data: claimed, error: plantError } = await supabaseServiceRole .from('plants') .update({ adoption_status: 'adopted', adopted_by: application.adopter_id, adopted_at: now, }) .eq('id', application.plant_id) .neq('adoption_status', 'adopted') .select('id'); if (plantError) { console.error('approve: failed to update plant:', plantError); return serverError(res, 'Could not approve the adoption'); } if (!claimed || claimed.length === 0) { return error(res, 'This plant has already been adopted', 409, 'CONFLICT'); } // 2. Approve this application const { error: approveError } = await supabaseServiceRole .from('adoptions') .update({ status: 'approved', reviewed_at: now }) .eq('id', req.params.id); if (approveError) { console.error('approve: failed to update application:', approveError); // Undo the claim so the plant is not left adopted with no approved application. await supabaseServiceRole .from('plants') .update({ adoption_status: 'pending', adopted_by: null, adopted_at: null }) .eq('id', application.plant_id); return serverError(res, 'Could not approve the adoption'); } // 3. Put the plant in the adopter's garden (drives care alerts). This row // belongs to the adopter, so the NGO's own client cannot create it. const { error: gardenError } = await supabaseServiceRole .from('user_plants') .upsert( { user_id: application.adopter_id, plant_id: application.plant_id }, { onConflict: 'user_id,plant_id' } ); if (gardenError) { console.error('approve: failed to add plant to adopter garden:', gardenError); } // 4. Auto-reject all other pending applications for this plant const { error: rejectOthersError } = await supabaseServiceRole .from('adoptions') .update({ status: 'rejected', review_notes: 'Plant was adopted by another user', reviewed_at: now }) .eq('plant_id', application.plant_id) .eq('status', 'pending') .neq('id', req.params.id); if (rejectOthersError) { console.error('approve: failed to reject other applications:', rejectOthersError); } // Notify adopter await notifyAdoptionResult({ adopterId: application.adopter_id, plantName: application.plants.plant_name, ngoName: req.user.displayName || req.user.username, status: 'approved', }); return success(res, { id: req.params.id, status: 'approved' }); } catch (err) { console.error('approve error:', err); return serverError(res); } } /** * PATCH /api/adoptions/:id/reject — NGO rejects adoption */ async function reject(req, res) { try { const { review_notes } = req.body; const { data: application } = await supabaseAdmin .from('adoptions') .select('*, plants!inner(plant_name, ngo_id)') .eq('id', req.params.id) .eq('status', 'pending') .maybeSingle(); if (!application) return notFound(res, 'Application not found or not pending'); if (application.ngo_id !== req.user.id) return forbidden(res, 'Only the plant owner can reject'); const { data: rejected, error: rejectError } = await supabaseServiceRole .from('adoptions') .update({ status: 'rejected', review_notes: review_notes || null, reviewed_at: new Date().toISOString(), }) .eq('id', req.params.id) .eq('status', 'pending') .select('id'); if (rejectError) { console.error('reject: failed to update application:', rejectError); return serverError(res, 'Could not reject the application'); } if (!rejected || rejected.length === 0) { return notFound(res, 'Application not found or not pending'); } // Check if there are any other pending applications const { count, error: countError } = await supabaseServiceRole .from('adoptions') .select('id', { count: 'exact', head: true }) .eq('plant_id', application.plant_id) .eq('status', 'pending'); // If no more pending apps, revert plant to available (never an adopted one) if (!countError && !count) { const { error: plantError } = await supabaseServiceRole .from('plants') .update({ adoption_status: 'available' }) .eq('id', application.plant_id) .eq('adoption_status', 'pending'); if (plantError) { console.error('reject: failed to reopen plant:', plantError); } } // Notify adopter await notifyAdoptionResult({ adopterId: application.adopter_id, plantName: application.plants.plant_name, ngoName: req.user.displayName || req.user.username, status: 'rejected', }); return success(res, { id: req.params.id, status: 'rejected' }); } catch (err) { console.error('reject error:', err); return serverError(res); } } module.exports = { apply, myAdoptions, getAdoption, approve, reject };