File size: 10,674 Bytes
55ffa7e
83f4356
 
 
55ffa7e
 
 
 
 
 
 
 
 
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
 
 
 
 
 
 
83f4356
55ffa7e
 
 
83f4356
 
 
 
 
55ffa7e
 
 
 
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
 
 
83f4356
 
 
 
 
 
 
 
55ffa7e
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
83f4356
 
 
 
55ffa7e
83f4356
55ffa7e
 
 
83f4356
 
 
 
55ffa7e
83f4356
55ffa7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83f4356
55ffa7e
 
 
 
 
 
 
 
 
 
 
 
 
6808cac
 
 
 
 
 
55ffa7e
 
 
 
 
 
83f4356
55ffa7e
83f4356
 
 
 
55ffa7e
 
 
 
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
83f4356
 
 
 
55ffa7e
83f4356
 
 
 
 
 
55ffa7e
 
 
 
 
 
 
 
 
 
 
83f4356
 
55ffa7e
83f4356
 
 
 
 
55ffa7e
 
 
83f4356
 
55ffa7e
 
 
 
 
 
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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 };