import { Request, Response } from 'express';
import prisma from '../lib/prisma';

export class BookmarksController {
    static async getAll(req: Request, res: Response) {
        try {
            const userId = (req as any).user?.userId;
            if (!userId) {
                return res.status(401).json({ success: false, error: 'Unauthorized' });
            }

            const messages = await prisma.savedMessage.findMany({
                where: { userId },
                orderBy: { createdAt: 'desc' },
            });

            return res.json({ success: true, data: messages });
        } catch (error) {
            console.error('Failed to get bookmarks:', error);
            return res.status(500).json({ success: false, error: 'Internal server error' });
        }
    }

    static async create(req: Request, res: Response) {
        try {
            const userId = (req as any).user?.userId;
            if (!userId) {
                return res.status(401).json({ success: false, error: 'Unauthorized' });
            }

            const { content, role } = req.body;
            if (!content) {
                return res.status(400).json({ success: false, error: 'Content is required' });
            }

            const message = await prisma.savedMessage.create({
                data: {
                    userId,
                    content,
                    role: role || 'model',
                },
            });

            return res.json({ success: true, data: message });
        } catch (error) {
            console.error('Failed to create bookmark:', error);
            return res.status(500).json({ success: false, error: 'Internal server error' });
        }
    }

    static async delete(req: Request, res: Response) {
        try {
            const userId = (req as any).user?.userId;
            if (!userId) {
                return res.status(401).json({ success: false, error: 'Unauthorized' });
            }

            const { id } = req.params;

            // Verify ownership
            const existing = await prisma.savedMessage.findFirst({
                where: { id, userId },
            });

            if (!existing) {
                return res.status(404).json({ success: false, error: 'Bookmark not found' });
            }

            await prisma.savedMessage.delete({
                where: { id },
            });

            return res.json({ success: true });
        } catch (error) {
            console.error('Failed to delete bookmark:', error);
            return res.status(500).json({ success: false, error: 'Internal server error' });
        }
    }
}
