File size: 8,970 Bytes
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6145bc
 
dff8169
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b638a
 
 
 
 
 
 
 
 
 
 
 
8eedd8d
 
 
 
 
 
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eedd8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b638a
 
 
 
 
 
 
 
 
 
 
c3e1e0e
97b638a
c3e1e0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b638a
55ffa7e
 
c3e1e0e
97b638a
 
 
 
 
 
 
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
const { supabaseAdmin } = require('../config/supabase');
const { success, created, error, notFound, forbidden, serverError } = require('../utils/response');
const { parsePagination } = require('../utils/pagination');
const { uploadMultipleToStorage } = require('../services/storage.service');

/**
 * POST /api/plants β€” create a new plant (NGO only)
 */
async function createPlant(req, res) {
  try {
    const { plant_name, species, description, latitude, longitude, address, planted_date, care_info } = req.body;

    // Upload images to Supabase Storage
    let imageUrls = [];
    if (req.files && req.files.length > 0) {
      imageUrls = await uploadMultipleToStorage('plant-images', req.files);
    }

    // Parse care_info if it's a string (from form-data)
    let parsedCareInfo = care_info;
    if (typeof care_info === 'string') {
      try { parsedCareInfo = JSON.parse(care_info); } catch { parsedCareInfo = null; }
    }

    const { data, error: dbError } = await supabaseAdmin
      .from('plants')
      .insert({
        ngo_id: req.user.id,
        plant_name,
        species: species || null,
        description: description || null,
        image_urls: imageUrls,
        latitude: latitude ? parseFloat(latitude) : null,
        longitude: longitude ? parseFloat(longitude) : null,
        // `location` is trigger-maintained from latitude/longitude β€” do not set it here
        address: address || null,
        planted_date: planted_date || new Date().toISOString().split('T')[0],
        care_info: parsedCareInfo || null,
      })
      .select()
      .single();

    if (dbError) {
      console.error('createPlant error:', dbError);
      return error(res, dbError.message, 400);
    }

    return created(res, data);
  } catch (err) {
    console.error('createPlant error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/plants β€” list plants (paginated, filterable)
 */
async function listPlants(req, res) {
  try {
    const { page, limit, offset } = parsePagination(req.query);
    const { status, ngo_id } = req.query;

    let query = supabaseAdmin
      .from('plants')
      .select('*, profiles!plants_ngo_id_fkey(username, display_name)', { count: 'exact' });

    if (status) query = query.eq('adoption_status', status);
    if (ngo_id) query = query.eq('ngo_id', ngo_id);

    const { data, error: dbError, count } = await query
      .order('created_at', { ascending: false })
      .range(offset, offset + limit - 1);

    if (dbError) return error(res, dbError.message, 400);

    return success(res, data, { page, limit, total: count });
  } catch (err) {
    console.error('listPlants error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/plants/:id β€” get single plant details
 */
async function getPlant(req, res) {
  try {
    const { data, error: dbError } = await supabaseAdmin
      .from('plants')
      .select('*, profiles!plants_ngo_id_fkey(username, display_name, avatar_url)')
      .eq('id', req.params.id)
      .single();

    if (dbError || !data) return notFound(res, 'Plant not found');

    return success(res, data);
  } catch (err) {
    console.error('getPlant error:', err);
    return serverError(res);
  }
}

/**
 * PUT /api/plants/:id β€” update plant (NGO owner only)
 */
async function updatePlant(req, res) {
  try {
    const { plant_name, species, description, address, care_info } = req.body;

    // Verify ownership
    const { data: existing } = await supabaseAdmin
      .from('plants')
      .select('ngo_id')
      .eq('id', req.params.id)
      .single();

    if (!existing) return notFound(res, 'Plant not found');
    if (existing.ngo_id !== req.user.id) return forbidden(res, 'You can only edit your own plants');

    const updates = { updated_at: new Date().toISOString() };
    if (plant_name !== undefined) updates.plant_name = plant_name;
    if (species !== undefined) updates.species = species;
    if (description !== undefined) updates.description = description;
    if (address !== undefined) updates.address = address;
    if (care_info !== undefined) {
      updates.care_info = typeof care_info === 'string' ? JSON.parse(care_info) : care_info;
    }

    const { data, error: dbError } = await supabaseAdmin
      .from('plants')
      .update(updates)
      .eq('id', req.params.id)
      .select()
      .single();

    if (dbError) return error(res, dbError.message, 400);

    return success(res, data);
  } catch (err) {
    console.error('updatePlant error:', err);
    return serverError(res);
  }
}

/**
 * DELETE /api/plants/:id β€” delete plant (NGO owner, only if available)
 */
async function deletePlant(req, res) {
  try {
    const { data: existing } = await supabaseAdmin
      .from('plants')
      .select('ngo_id, adoption_status')
      .eq('id', req.params.id)
      .single();

    if (!existing) return notFound(res, 'Plant not found');
    if (existing.ngo_id !== req.user.id) return forbidden(res, 'You can only delete your own plants');
    if (existing.adoption_status !== 'available') {
      return error(res, 'Cannot delete a plant with pending or completed adoptions', 400);
    }

    // The status filter closes the gap between the check above and the delete:
    // an application arriving in between must not lose its plant.
    const { data: deleted, error: deleteError } = await supabaseAdmin
      .from('plants')
      .delete()
      .eq('id', req.params.id)
      .eq('adoption_status', 'available')
      .select('id');

    if (deleteError) {
      console.error('deletePlant error:', deleteError);
      return serverError(res, 'Could not delete the plant');
    }
    if (!deleted || deleted.length === 0) {
      return error(res, 'Cannot delete a plant with pending or completed adoptions', 400);
    }

    return success(res, { message: 'Plant deleted successfully' });
  } catch (err) {
    console.error('deletePlant error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/plants/nearby β€” PostGIS radius search
 * Query: ?lat=19.07&lng=72.87&radius=10000 (meters, default 10km)
 */
/**
 * GET /api/plants/nearby β€” PostGIS radius search
 * Query: ?lat=19.07&lng=72.87&radius=10000 (meters, default 10km)
 * Marks plants the requesting user has adopted so the "near me" map
 * can render them in a distinct colour (issue #209).
 */
async function nearbyPlants(req, res) {
  try {
    const lat = parseFloat(req.query.lat);
    const lng = parseFloat(req.query.lng);
    const radius = parseInt(req.query.radius, 10) || 10000;

    const { data, error: dbError } = await supabaseAdmin.rpc('nearby_plants', {
      user_lat: lat,
      user_lng: lng,
      radius_meters: radius,
    });

    if (dbError) {
      console.error('nearbyPlants RPC error:', dbError);
      return error(res, dbError.message, 400);
    }

    // Cross-reference against the requesting user's own adoptions so the
    // client can render "my plant" markers differently without a second
    // round trip.
    const { data: myAdoptions } = await supabaseAdmin
      .from('adoptions')
      .select('plant_id')
      .eq('adopter_id', req.user.id)
      .eq('status', 'approved');

    const myPlantIds = new Set((myAdoptions || []).map((a) => a.plant_id));
    const enriched = (data || []).map((plant) => ({
      ...plant,
      is_mine: myPlantIds.has(plant.id),
    }));

    return success(res, enriched, { radius_meters: radius, total: enriched.length });
  } catch (err) {
    console.error('nearbyPlants error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/plants/map β€” all plants with location + status for map rendering
 */
async function mapPlants(req, res) {
  try {
    const { minLng, minLat, maxLng, maxLat } = req.query;

    if ([minLng, minLat, maxLng, maxLat].some((v) => v === undefined)) {
      return error(res, 'minLng, minLat, maxLng, maxLat query params are required', 400);
    }

    const bbox = {
      min_lng: parseFloat(minLng),
      min_lat: parseFloat(minLat),
      max_lng: parseFloat(maxLng),
      max_lat: parseFloat(maxLat),
    };

    if (Object.values(bbox).some((v) => Number.isNaN(v))) {
      return error(res, 'bbox query params must be valid numbers', 400);
    }

    const MAX_MAP_RESULTS = 500;

    const { data, error: dbError } = await supabaseAdmin.rpc('plants_in_bbox', {
      ...bbox,
      max_results: MAX_MAP_RESULTS,
    });

    if (dbError) {
      console.error('mapPlants RPC error:', dbError);
      return error(res, dbError.message, 400);
    }

    // Authenticated endpoint: cache in the user's browser only, never a shared cache.
    res.set('Cache-Control', 'private, max-age=60, stale-while-revalidate=60');
    return success(res, data, { truncated: (data?.length || 0) >= MAX_MAP_RESULTS });
  } catch (err) {
    console.error('mapPlants error:', err);
    return serverError(res);
  }
}

module.exports = { createPlant, listPlants, getPlant, updatePlant, deletePlant, nearbyPlants, mapPlants };