File size: 3,614 Bytes
8a6248c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { generateAIContent } from '../utils/aiHelper.js';
import { extractLanguage, getLanguageName } from '../utils/aiOrchestrator.js';
import dotenv from 'dotenv';
import mongoose from 'mongoose';

const notificationSchema = new mongoose.Schema({
    userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    title: { type: String, required: true },
    message: { type: String, required: true },
    type: { type: String, default: 'general' },
    read: { type: Boolean, default: false },
    link: String,
}, { timestamps: true });

const Notification = mongoose.models.Notification || mongoose.model('Notification', notificationSchema);

export const getFarmingAlerts = async (req, res) => {
    dotenv.config();
    
    const { region } = req.query;
    const lang = extractLanguage(req);
    const langName = getLanguageName(lang);
    const langInstruction = lang !== 'en' ? `\nRespond STRICTLY in ${langName} language.` : '';

    try {
        const promptText = `
            Please provide a maximum of 2 short and recent farming alerts or notifications in max 5-6 words related to farming weather and conditions, specifically for the region of ${region}.

            Focus on:
            - Important weather-related alerts relevant to farming today.
            - Any immediate farming precautions or actions farmers should take.

            Keep each alert clear, brief, and farmer-friendly. Thank you!${langInstruction}
        `;

        const alerts = await generateAIContent(promptText.trim());
        res.status(200).json({ alerts });
    } catch (err) {
        console.error("Error fetching farming alerts: ", err);
        res.status(500).json({ error: "Failed to fetch alerts" });
    }
};

export const listNotifications = async (req, res) => {
    try {
        const userId = req.user?._id;

        if (!userId) {
            return res.status(401).json({ success: false, error: 'Unauthorized' });
        }

        const notifications = await Notification.find({ userId }).sort('-createdAt').limit(20).lean();
        const unread = notifications.filter((n) => !n.read).length;

        return res.status(200).json({
            success: true,
            data: {
                notifications,
                unread,
            },
        });
    } catch (err) {
        return res.status(500).json({ success: false, error: err.message });
    }
};

export const seedNotification = async (req, res) => {
    try {
        const userId = req.user?._id;
        if (!userId) {
            return res.status(401).json({ success: false, error: 'Unauthorized' });
        }

        const { title, message, type = 'general', link } = req.body || {};
        if (!title || !message) {
            return res.status(400).json({ success: false, error: 'title and message are required' });
        }

        const created = await Notification.create({ userId, title, message, type, link });
        return res.status(201).json({ success: true, data: created });
    } catch (err) {
        return res.status(500).json({ success: false, error: err.message });
    }
};

export const markNotificationRead = async (req, res) => {
    try {
        const userId = req.user?._id;
        const { id } = req.params;
        if (!userId) {
            return res.status(401).json({ success: false, error: 'Unauthorized' });
        }

        await Notification.updateOne({ _id: id, userId }, { $set: { read: true } });
        return res.status(200).json({ success: true });
    } catch (err) {
        return res.status(500).json({ success: false, error: err.message });
    }
};