File size: 5,429 Bytes
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
const { supabaseAdmin } = require('../config/supabase');
const { success, notFound, forbidden, error, serverError } = require('../utils/response');

/**
 * GET /api/profiles/:userId — view anyone's profile
 */
async function getProfile(req, res) {
  try {
    const { data: profile, error: dbError } = await supabaseAdmin
      .from('profiles')
      .select('id, role, username, display_name, avatar_url, bio, created_at')
      .eq('id', req.params.userId)
      .single();

    if (dbError || !profile) return notFound(res, 'User not found');

    let ngoProfile = null;
    if (profile.role === 'ngo') {
      const { data } = await supabaseAdmin
        .from('ngo_profiles')
        .select('org_name, mission, website, status')
        .eq('id', profile.id)
        .single();
      ngoProfile = data;
    }

    // Get counts
    const [followersResult, followingResult, plantsResult, postsResult] = await Promise.all([
      supabaseAdmin.from('follows').select('follower_id', { count: 'exact', head: true }).eq('following_id', profile.id),
      supabaseAdmin.from('follows').select('following_id', { count: 'exact', head: true }).eq('follower_id', profile.id),
      supabaseAdmin.from('plants').select('id', { count: 'exact', head: true }).eq('ngo_id', profile.id),
      supabaseAdmin.from('posts').select('id', { count: 'exact', head: true }).eq('author_id', profile.id),
    ]);

    // Check if current user follows this profile
    const { data: followCheck } = await supabaseAdmin
      .from('follows')
      .select('follower_id')
      .eq('follower_id', req.user.id)
      .eq('following_id', profile.id)
      .single();

    return success(res, {
      ...profile,
      ngo_profile: ngoProfile,
      followers_count: followersResult.count || 0,
      following_count: followingResult.count || 0,
      plants_count: plantsResult.count || 0,
      posts_count: postsResult.count || 0,
      is_following: !!followCheck,
    });
  } catch (err) {
    console.error('getProfile error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/profiles/:userId/posts — posts by user
 */
async function getUserPosts(req, res) {
  try {
    const { data, error: dbError } = await supabaseAdmin
      .from('posts')
      .select('*, profiles!inner(username, display_name, avatar_url)')
      .eq('author_id', req.params.userId)
      .order('created_at', { ascending: false });

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

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

/**
 * GET /api/profiles/:userId/plants — plants by NGO
 */
async function getUserPlants(req, res) {
  try {
    const { data, error: dbError } = await supabaseAdmin
      .from('plants')
      .select('*')
      .eq('ngo_id', req.params.userId)
      .order('created_at', { ascending: false });

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

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

/**
 * POST /api/profiles/:userId/follow — follow a user/NGO
 */
async function follow(req, res) {
  try {
    const targetId = req.params.userId;
    if (targetId === req.user.id) return error(res, 'You cannot follow yourself', 400);

    const { error: dbError } = await supabaseAdmin
      .from('follows')
      .insert({ follower_id: req.user.id, following_id: targetId });

    if (dbError) {
      if (dbError.code === '23505') return error(res, 'Already following', 409, 'CONFLICT');
      return error(res, dbError.message, 400);
    }

    return success(res, { following: true });
  } catch (err) {
    console.error('follow error:', err);
    return serverError(res);
  }
}

/**
 * DELETE /api/profiles/:userId/follow — unfollow
 */
async function unfollow(req, res) {
  try {
    await supabaseAdmin
      .from('follows')
      .delete()
      .eq('follower_id', req.user.id)
      .eq('following_id', req.params.userId);

    return success(res, { following: false });
  } catch (err) {
    console.error('unfollow error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/profiles/:userId/followers
 */
async function getFollowers(req, res) {
  try {
    const { data, error: dbError } = await supabaseAdmin
      .from('follows')
      .select('profiles!follows_follower_id_fkey(id, username, display_name, avatar_url, role)')
      .eq('following_id', req.params.userId);

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

    const followers = (data || []).map((f) => f.profiles);
    return success(res, followers);
  } catch (err) {
    console.error('getFollowers error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/profiles/:userId/following
 */
async function getFollowing(req, res) {
  try {
    const { data, error: dbError } = await supabaseAdmin
      .from('follows')
      .select('profiles!follows_following_id_fkey(id, username, display_name, avatar_url, role)')
      .eq('follower_id', req.params.userId);

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

    const following = (data || []).map((f) => f.profiles);
    return success(res, following);
  } catch (err) {
    console.error('getFollowing error:', err);
    return serverError(res);
  }
}

module.exports = { getProfile, getUserPosts, getUserPlants, follow, unfollow, getFollowers, getFollowing };