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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
const prisma = require('../config/database');
const axios = require('axios');
const Joi = require('joi');
const { AI_SERVICE_URL } = process.env;

/**
 * POST /api/shipments/create - Create shipment (calls XGBoost)
 */
const createShipment = async (req, res) => {
  try {
    // Validation
    const schema = Joi.object({
      pickupLat: Joi.number().required(),
      pickupLng: Joi.number().required(),
      pickupLocation: Joi.string().max(200).required(),
      dropLat: Joi.number().required(),
      dropLng: Joi.number().required(),
      dropLocation: Joi.string().max(200).required(),
      cargoType: Joi.string().valid(
        'Electronics', 'Industrial Machinery', 'Textiles',
        'Automotive Parts', 'FMCG Products', 'Pharmaceuticals',
        'Steel & Metal', 'Agricultural Products', 'Furniture'
      ).required(),
      cargoWeight: Joi.number().min(0.1).max(50).required(),
      specialInstructions: Joi.string().max(500).optional(),
      priority: Joi.string().valid('LOW', 'MEDIUM', 'HIGH').default('LOW'),
    });

    const { error } = schema.validate(req.body);
    if (error) {
      return res.status(400).json({
        success: false,
        message: error.details[0].message,
      });
    }

    const {
      pickupLat, pickupLng, pickupLocation,
      dropLat, dropLng, dropLocation,
      cargoType, cargoWeight, specialInstructions, priority
    } = req.body;

    // Calculate distance (Haversine formula)
    const distanceKm = calculateDistance(
      { lat: pickupLat, lng: pickupLng },
      { lat: dropLat, lng: dropLng }
    );

    // Call XGBoost AI Pricing Service
    let aiPriceResponse;
    try {
      aiPriceResponse = await axios.post(`${AI_SERVICE_URL}/pricing/predict`, {
        distance_km: distanceKm,
        cargo_weight_tonnes: cargoWeight,
        cargo_type: cargoType,
        pickup_city: extractCity(pickupLocation),
        drop_city: extractCity(dropLocation),
        time_of_day: new Date().getHours() < 18 ? 'day' : 'night',
        day_of_week: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][new Date().getDay()],
        fuel_price: 98.5,
        traffic_level: 'medium',
        urgency: priority.toLowerCase(),
      }, { timeout: 5000 });
    } catch (aiError) {
      console.log('❌ AI service unavailable, using fallback pricing');
      // Fallback pricing formula
      aiPriceResponse = {
        data: {
          predicted_price: Math.round((distanceKm * 18 + cargoWeight * 100) / 10) * 10,
          confidence: 0.75,
          price_breakdown: {
            base_rate: Math.round(distanceKm * 15),
            distance_premium: Math.round(distanceKm * 2),
            weight_premium: Math.round(cargoWeight * 80),
          }
        }
      };
    }

    // Create shipment
    const shipment = await prisma.shipment.create({
      data: {
        shipperId: req.user.id,
        pickupLocation,
        pickupLat,
        pickupLng,
        dropLocation,
        dropLat,
        dropLng,
        cargoType,
        cargoWeight,
        specialInstructions: specialInstructions || null,
        estimatedPrice: aiPriceResponse.data.predicted_price,
        status: 'PENDING',
        priority,
        isMarketplaceLoad: Math.random() > 0.7, // 30% chance
      },
      include: {
        shipper: {
          select: { name: true, phone: true }
        }
      }
    });

    res.status(201).json({
      success: true,
      message: 'Shipment created successfully',
      data: {
        id: shipment.id,
        status: shipment.status,
        estimatedPrice: shipment.estimatedPrice,
        aiConfidence: aiPriceResponse.data.confidence,
        distanceKm,
        priceBreakdown: aiPriceResponse.data.price_breakdown,
        shipment,
      },
    });
  } catch (error) {
    console.error('Create shipment error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to create shipment',
    });
  }
};

/**
 * GET /api/shipments/my-shipments - List shipper's shipments
 */
const getMyShipments = async (req, res) => {
  try {
    const shipments = await prisma.shipment.findMany({
      where: { shipperId: req.user.id },
      orderBy: { createdAt: 'desc' },
      include: {
        dispatcher: {
          select: { name: true }
        },
        delivery: {
          include: {
            driver: {
              select: { name: true, rating: true, phone: true }
            },
            truck: {
              select: { licensePlate: true, model: true }
            }
          }
        }
      },
      take: 20,
    });

    res.status(200).json({
      success: true,
      data: shipments,
      count: shipments.length,
    });
  } catch (error) {
    console.error('Get shipments error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch shipments',
    });
  }
};

/**
 * GET /api/shipments/:id - Get single shipment
 */
const getShipment = async (req, res) => {
  try {
    const { id } = req.params;

    const shipment = await prisma.shipment.findUnique({
      where: { id },
      include: {
        shipper: {
          select: { name: true, phone: true }
        },
        dispatcher: {
          select: { name: true }
        },
        delivery: {
          include: {
            driver: {
              select: { name: true, rating: true, phone: true }
            },
            truck: {
              select: { licensePlate: true, model: true }
            }
          }
        }
      },
    });

    if (!shipment) {
      return res.status(404).json({
        success: false,
        message: 'Shipment not found',
      });
    }

    // Only shipper or dispatcher can view
    if (shipment.shipperId !== req.user.id && req.user.role !== 'DISPATCHER') {
      return res.status(403).json({
        success: false,
        message: 'Access denied',
      });
    }

    res.status(200).json({
      success: true,
      data: shipment,
    });
  } catch (error) {
    console.error('Get shipment error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch shipment',
    });
  }
};

/**
 * PUT /api/shipments/:id/cancel - Cancel pending shipment
 */
const cancelShipment = async (req, res) => {
  try {
    const { id } = req.params;

    const shipment = await prisma.shipment.findUnique({
      where: { id },
    });

    if (!shipment) {
      return res.status(404).json({
        success: false,
        message: 'Shipment not found',
      });
    }

    // Only shipper can cancel their own shipment
    if (shipment.shipperId !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Access denied',
      });
    }

    // Only cancel PENDING shipments
    if (!['PENDING', 'AWAITING_DISPATCHER'].includes(shipment.status)) {
      return res.status(400).json({
        success: false,
        message: 'Only pending shipments can be cancelled',
      });
    }

    await prisma.shipment.update({
      where: { id },
      data: { status: 'CANCELLED' },
    });

    res.status(200).json({
      success: true,
      message: 'Shipment cancelled successfully',
    });
  } catch (error) {
    console.error('Cancel shipment error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to cancel shipment',
    });
  }
};

/**
 * GET /api/shipments/pending - Get all pending shipments for drivers
 */
const getPendingShipments = async (req, res) => {
  try {
    const shipments = await prisma.shipment.findMany({
      where: {
        status: 'PENDING',
      },
      orderBy: { createdAt: 'desc' },
      include: {
        shipper: {
          select: { name: true, phone: true }
        }
      },
      take: 20,
    });

    res.status(200).json({
      success: true,
      data: shipments,
      count: shipments.length,
    });
  } catch (error) {
    console.error('Get pending shipments error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch pending shipments',
    });
  }
};

/**
 * POST /api/shipments/:id/accept - Driver accepts a shipment
 */
const acceptShipment = async (req, res) => {
  try {
    const { id } = req.params;
    const driverId = req.user.id;

    const shipment = await prisma.shipment.findUnique({
      where: { id },
    });

    if (!shipment) {
      return res.status(404).json({
        success: false,
        message: 'Shipment not found',
      });
    }

    if (shipment.status !== 'PENDING') {
      return res.status(400).json({
        success: false,
        message: 'Shipment already assigned',
      });
    }

    // Get driver's truck
    const truck = await prisma.truck.findFirst({
      where: { driverId },
    });

    if (!truck) {
      return res.status(400).json({
        success: false,
        message: 'No truck assigned to driver',
      });
    }

    // Create delivery and update shipment in transaction
    const result = await prisma.$transaction(async (tx) => {
      // Update shipment status
      const updatedShipment = await tx.shipment.update({
        where: { id },
        data: { status: 'ASSIGNED' },
      });

      // Create delivery record
      const delivery = await tx.delivery.create({
        data: {
          driverId,
          truckId: truck.id,
          shipmentId: id,
          pickupLocation: shipment.pickupLocation,
          pickupLat: shipment.pickupLat,
          pickupLng: shipment.pickupLng,
          dropLocation: shipment.dropLocation,
          dropLat: shipment.dropLat,
          dropLng: shipment.dropLng,
          cargoType: shipment.cargoType,
          cargoWeight: shipment.cargoWeight,
          status: 'ALLOCATED',
          estimatedPrice: shipment.estimatedPrice || 0,
        },
      });

      return { shipment: updatedShipment, delivery };
    });

    res.status(200).json({
      success: true,
      message: 'Shipment accepted! Check your deliveries.',
      data: result,
    });
  } catch (error) {
    console.error('Accept shipment error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to accept shipment',
    });
  }
};

// Helper functions
const calculateDistance = (point1, point2) => {
  const R = 6371; // Earth's radius in km
  const dLat = (point2.lat - point1.lat) * Math.PI / 180;
  const dLng = (point2.lng - point1.lng) * Math.PI / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(point1.lat * Math.PI / 180) * Math.cos(point2.lat * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return Math.round(R * c);
};

const extractCity = (location) => {
  const cities = ['Mumbai', 'Delhi', 'Bangalore', 'Pune', 'Hyderabad', 'Chennai'];
  const city = cities.find(city => location.includes(city));
  return city || 'Other';
};

module.exports = {
  createShipment,
  getMyShipments,
  getShipment,
  cancelShipment,
  getPendingShipments,
  acceptShipment,
};