File size: 5,153 Bytes
d3ef35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253c059
 
 
 
 
 
 
 
 
 
 
d3ef35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Wishlist Controller - User favorites/saved destinations
 */
const { getPool } = require('../db');

/**
 * Get user's wishlist
 */
async function listWishlist(req, res) {
  const pool = getPool();
  if (!pool) return res.status(500).json({ error: 'Database not connected' });
  
  const userId = req.user.id || req.user.sub;
  
  try {
    // Create table if not exists
    await pool.query(`
      CREATE TABLE IF NOT EXISTS wishlists (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        destination_id TEXT NOT NULL,
        created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
        UNIQUE(user_id, destination_id)
      )
    `);
    
    const result = await pool.query(
      `SELECT w.id, w.destination_id, w.created_at,
              d.name, d.slug, d.description, d.category, d.district, d.rating
       FROM wishlists w
       LEFT JOIN destinations d ON w.destination_id = d.id
       WHERE w.user_id = $1
       ORDER BY w.created_at DESC`,
      [userId]
    );
    
    res.json({ 
      success: true, 
      wishlist: result.rows.map(row => ({
        id: row.id,
        destinationId: row.destination_id,
        createdAt: row.created_at,
        destination: row.name ? {
          id: row.destination_id,
          name: row.name,
          slug: row.slug,
          description: row.description,
          category: row.category,
          district: row.district,
          rating: row.rating
        } : null
      }))
    });
  } catch (error) {
    console.error('[Wishlist List Error]', error.message);
    res.status(500).json({ error: 'Failed to fetch wishlist' });
  }
}

/**
 * Add item to wishlist
 */
async function addToWishlist(req, res) {
  const pool = getPool();
  if (!pool) return res.status(500).json({ error: 'Database not connected' });
  
  const userId = req.user.id || req.user.sub;
  const { destination_id } = req.body;
  
  if (!destination_id) {
    return res.status(400).json({ error: 'destination_id is required' });
  }
  
  try {
    // Create table if not exists
    await pool.query(`
      CREATE TABLE IF NOT EXISTS wishlists (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        destination_id TEXT NOT NULL,
        created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
        UNIQUE(user_id, destination_id)
      )
    `);
    
    const result = await pool.query(
      `INSERT INTO wishlists (user_id, destination_id)
       VALUES ($1, $2)
       ON CONFLICT (user_id, destination_id) DO NOTHING
       RETURNING id, destination_id, created_at`,
      [userId, destination_id]
    );
    
    if (result.rows.length === 0) {
      return res.json({ success: true, message: 'Already in wishlist' });
    }
    
    res.status(201).json({ 
      success: true, 
      message: 'Added to wishlist',
      item: result.rows[0]
    });
  } catch (error) {
    console.error('[Wishlist Add Error]', error.message);
    res.status(500).json({ error: 'Failed to add to wishlist' });
  }
}

/**
 * Remove item from wishlist
 */
async function removeFromWishlist(req, res) {
  const pool = getPool();
  if (!pool) return res.status(500).json({ error: 'Database not connected' });
  
  const userId = req.user.id || req.user.sub;
  const { destinationId } = req.params;
  
  try {
    const result = await pool.query(
      'DELETE FROM wishlists WHERE user_id = $1 AND destination_id = $2 RETURNING id',
      [userId, destinationId]
    );
    
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Item not found in wishlist' });
    }
    
    res.json({ success: true, message: 'Removed from wishlist' });
  } catch (error) {
    console.error('[Wishlist Remove Error]', error.message);
    res.status(500).json({ error: 'Failed to remove from wishlist' });
  }
}

/**
 * Check if destination is in wishlist
 */
async function checkWishlist(req, res) {
  const pool = getPool();
  if (!pool) return res.status(500).json({ error: 'Database not connected' });
  
  const userId = req.user.id || req.user.sub;
  const { destinationId } = req.params;
  
  try {
    // Create table if not exists (to prevent 500 if checked before any add)
    await pool.query(`
      CREATE TABLE IF NOT EXISTS wishlists (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        destination_id TEXT NOT NULL,
        created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
        UNIQUE(user_id, destination_id)
      )
    `);

    const result = await pool.query(
      'SELECT id FROM wishlists WHERE user_id = $1 AND destination_id = $2',
      [userId, destinationId]
    );
    
    res.json({ 
      success: true, 
      inWishlist: result.rows.length > 0 
    });
  } catch (error) {
    console.error('[Wishlist Check Error]', error.message);
    res.status(500).json({ error: 'Failed to check wishlist' });
  }
}

module.exports = {
  listWishlist,
  addToWishlist,
  removeFromWishlist,
  checkWishlist
};