import { Router, Request, Response } from 'express';
import { prisma } from '../lib/prisma.js';
import { isAuthenticated } from '../middleware/auth.js';
import { Visibility } from '@prisma/client';

const router = Router();

/**
 * GET /api/documents
 * Get all documents for the authenticated user
 */
router.get('/', isAuthenticated, async (req: Request, res: Response) => {
  try {
    const userId = req.user?.id;

    const documents = await prisma.document.findMany({
      where: {
        ownerUserId: userId,
      },
      include: {
        pages: {
          include: {
            sentences: {
              include: {
                tokens: {
                  include: {
                    term: true,
                  },
                  orderBy: {
                    tokenIndex: 'asc',
                  },
                },
              },
              orderBy: {
                sentenceIndex: 'asc',
              },
            },
          },
          orderBy: {
            pageIndex: 'asc',
          },
        },
      },
      orderBy: {
        updatedAt: 'desc',
      },
    });

    res.json({ documents });
  } catch (error: any) {
    console.error('Error fetching documents:', error);
    res.status(500).json({ error: 'Failed to fetch documents', message: error.message });
  }
});

/**
 * GET /api/documents/:id
 * Get a single document by ID
 */
router.get('/:id', isAuthenticated, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const userId = req.user?.id;

    const document = await prisma.document.findFirst({
      where: {
        id,
        ownerUserId: userId,
      },
      include: {
        pages: {
          include: {
            sentences: {
              include: {
                tokens: {
                  include: {
                    term: {
                      include: {
                        media: true,
                      },
                    },
                  },
                  orderBy: {
                    tokenIndex: 'asc',
                  },
                },
              },
              orderBy: {
                sentenceIndex: 'asc',
              },
            },
          },
          orderBy: {
            pageIndex: 'asc',
          },
        },
      },
    });

    if (!document) {
      return res.status(404).json({ error: 'Document not found' });
    }

    res.json({ document });
  } catch (error: any) {
    console.error('Error fetching document:', error);
    res.status(500).json({ error: 'Failed to fetch document', message: error.message });
  }
});

/**
 * POST /api/documents
 * Create a new document
 */
router.post('/', isAuthenticated, async (req: Request, res: Response) => {
  try {
    const userId = req.user?.id;
    const { title, description, visibility = 'PRIVATE' } = req.body;

    if (!title) {
      return res.status(400).json({ error: 'Title is required' });
    }

    const document = await prisma.document.create({
      data: {
        title,
        description,
        visibility: visibility as Visibility,
        ownerUserId: userId,
        pages: {
          create: {
            pageIndex: 0,
            title: 'Stranica 1',
          },
        },
      },
      include: {
        pages: {
          include: {
            sentences: {
              include: {
                tokens: {
                  include: {
                    term: true,
                  },
                  orderBy: {
                    tokenIndex: 'asc',
                  },
                },
              },
              orderBy: {
                sentenceIndex: 'asc',
              },
            },
          },
          orderBy: {
            pageIndex: 'asc',
          },
        },
      },
    });

    res.status(201).json({ document });
  } catch (error: any) {
    console.error('Error creating document:', error);
    res.status(500).json({ error: 'Failed to create document', message: error.message });
  }
});

/**
 * PATCH /api/documents/:id
 * Update a document
 */
router.patch('/:id', isAuthenticated, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const userId = req.user?.id;
    const { title, description, visibility } = req.body;

    // Check if document exists and belongs to user
    const existingDoc = await prisma.document.findFirst({
      where: {
        id,
        ownerUserId: userId,
      },
    });

    if (!existingDoc) {
      return res.status(404).json({ error: 'Document not found' });
    }

    const document = await prisma.document.update({
      where: { id },
      data: {
        ...(title && { title }),
        ...(description !== undefined && { description }),
        ...(visibility && { visibility: visibility as Visibility }),
      },
      include: {
        pages: {
          include: {
            sentences: {
              include: {
                tokens: {
                  include: {
                    term: true,
                  },
                  orderBy: {
                    tokenIndex: 'asc',
                  },
                },
              },
              orderBy: {
                sentenceIndex: 'asc',
              },
            },
          },
          orderBy: {
            pageIndex: 'asc',
          },
        },
      },
    });

    res.json({ document });
  } catch (error: any) {
    console.error('Error updating document:', error);
    res.status(500).json({ error: 'Failed to update document', message: error.message });
  }
});

/**
 * DELETE /api/documents/:id
 * Delete a document
 */
router.delete('/:id', isAuthenticated, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const userId = req.user?.id;

    // Check if document exists and belongs to user
    const existingDoc = await prisma.document.findFirst({
      where: {
        id,
        ownerUserId: userId,
      },
    });

    if (!existingDoc) {
      return res.status(404).json({ error: 'Document not found' });
    }

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

    res.json({ message: 'Document deleted successfully' });
  } catch (error: any) {
    console.error('Error deleting document:', error);
    res.status(500).json({ error: 'Failed to delete document', message: error.message });
  }
});

export default router;

