"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const db_1 = require("../db");
const schema_1 = require("../db/schema");
const auth_1 = require("../middleware/auth");
const drizzle_orm_1 = require("drizzle-orm");
const router = (0, express_1.Router)();
// Middleware to check if user is admin
const requireAdmin = (req, res, next) => {
    if (req.user?.role !== 'admin') {
        return res.status(403).json({ error: "Admin access required" });
    }
    next();
};
// Get database statistics
router.get("/stats", auth_1.authenticateToken, requireAdmin, async (req, res) => {
    try {
        const [leadsData, usersData, activitiesData, tasksData, notificationsData] = await Promise.all([
            db_1.db.select().from(schema_1.leads),
            db_1.db.select().from(schema_1.users),
            db_1.db.select().from(schema_1.activities),
            db_1.db.select().from(schema_1.tasks),
            db_1.db.select().from(schema_1.notifications)
        ]);
        // Calculate lead status breakdown
        const leadStatusBreakdown = {};
        leadsData.forEach(lead => {
            leadStatusBreakdown[lead.status] = (leadStatusBreakdown[lead.status] || 0) + 1;
        });
        // Calculate user role breakdown
        const userRoleBreakdown = {};
        usersData.forEach(user => {
            const role = user.role || 'employee';
            userRoleBreakdown[role] = (userRoleBreakdown[role] || 0) + 1;
        });
        // Calculate activity type breakdown
        const activityTypeBreakdown = {};
        activitiesData.forEach(activity => {
            const type = activity.type || 'unknown';
            activityTypeBreakdown[type] = (activityTypeBreakdown[type] || 0) + 1;
        });
        res.json({
            tables: {
                leads: {
                    count: leadsData.length,
                    breakdown: leadStatusBreakdown
                },
                users: {
                    count: usersData.length,
                    breakdown: userRoleBreakdown
                },
                activities: {
                    count: activitiesData.length,
                    breakdown: activityTypeBreakdown
                },
                tasks: {
                    count: tasksData.length
                },
                notifications: {
                    count: notificationsData.length
                }
            },
            timestamp: new Date().toISOString()
        });
    }
    catch (error) {
        console.error("Error fetching database stats:", error);
        res.status(500).json({ error: "Failed to fetch database statistics" });
    }
});
// Get records from a specific table
router.get("/table/:tableName", auth_1.authenticateToken, requireAdmin, async (req, res) => {
    try {
        const { tableName } = req.params;
        const limit = parseInt(req.query.limit) || 50;
        const offset = parseInt(req.query.offset) || 0;
        let data = [];
        switch (tableName) {
            case 'leads':
                data = await db_1.db.select().from(schema_1.leads).orderBy((0, drizzle_orm_1.desc)(schema_1.leads.createdAt)).limit(limit).offset(offset);
                break;
            case 'users':
                data = await db_1.db.select().from(schema_1.users).orderBy((0, drizzle_orm_1.desc)(schema_1.users.createdAt)).limit(limit).offset(offset);
                break;
            case 'activities':
                data = await db_1.db.select().from(schema_1.activities).orderBy((0, drizzle_orm_1.desc)(schema_1.activities.createdAt)).limit(limit).offset(offset);
                break;
            case 'tasks':
                data = await db_1.db.select().from(schema_1.tasks).orderBy((0, drizzle_orm_1.desc)(schema_1.tasks.createdAt)).limit(limit).offset(offset);
                break;
            case 'notifications':
                data = await db_1.db.select().from(schema_1.notifications).orderBy((0, drizzle_orm_1.desc)(schema_1.notifications.createdAt)).limit(limit).offset(offset);
                break;
            default:
                return res.status(400).json({ error: "Invalid table name" });
        }
        res.json({
            tableName,
            count: data.length,
            limit,
            offset,
            data
        });
    }
    catch (error) {
        console.error(`Error fetching table ${req.params.tableName}:`, error);
        res.status(500).json({ error: "Failed to fetch table data" });
    }
});
// Create a new record in a table
router.post("/table/:tableName", auth_1.authenticateToken, requireAdmin, async (req, res) => {
    try {
        const { tableName } = req.params;
        const recordData = req.body;
        switch (tableName) {
            case 'leads':
                await db_1.db.insert(schema_1.leads).values(recordData);
                break;
            case 'users':
                await db_1.db.insert(schema_1.users).values(recordData);
                break;
            case 'activities':
                await db_1.db.insert(schema_1.activities).values(recordData);
                break;
            case 'tasks':
                await db_1.db.insert(schema_1.tasks).values(recordData);
                break;
            case 'notifications':
                await db_1.db.insert(schema_1.notifications).values(recordData);
                break;
            default:
                return res.status(400).json({ error: "Invalid table name" });
        }
        res.json({ success: true, message: "Record created successfully" });
    }
    catch (error) {
        console.error(`Error creating record in ${req.params.tableName}:`, error);
        res.status(500).json({ error: "Failed to create record" });
    }
});
// Update a record in a table
router.put("/table/:tableName/:id", auth_1.authenticateToken, requireAdmin, async (req, res) => {
    try {
        const { tableName, id } = req.params;
        const recordData = req.body;
        let affectedRows = 0;
        switch (tableName) {
            case 'leads':
                await db_1.db.update(schema_1.leads).set(recordData).where((0, drizzle_orm_1.eq)(schema_1.leads.id, id));
                break;
            case 'users':
                await db_1.db.update(schema_1.users).set(recordData).where((0, drizzle_orm_1.eq)(schema_1.users.id, id));
                break;
            case 'activities':
                await db_1.db.update(schema_1.activities).set(recordData).where((0, drizzle_orm_1.eq)(schema_1.activities.id, id));
                break;
            case 'tasks':
                await db_1.db.update(schema_1.tasks).set(recordData).where((0, drizzle_orm_1.eq)(schema_1.tasks.id, id));
                break;
            case 'notifications':
                await db_1.db.update(schema_1.notifications).set(recordData).where((0, drizzle_orm_1.eq)(schema_1.notifications.id, id));
                break;
            default:
                return res.status(400).json({ error: "Invalid table name" });
        }
        res.json({ success: true, message: "Record updated successfully" });
    }
    catch (error) {
        console.error(`Error updating record in ${req.params.tableName}:`, error);
        res.status(500).json({ error: "Failed to update record" });
    }
});
// Delete a record from a table
router.delete("/table/:tableName/:id", auth_1.authenticateToken, requireAdmin, async (req, res) => {
    try {
        const { tableName, id } = req.params;
        switch (tableName) {
            case 'leads':
                await db_1.db.delete(schema_1.leads).where((0, drizzle_orm_1.eq)(schema_1.leads.id, id));
                break;
            case 'users':
                await db_1.db.delete(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.id, id));
                break;
            case 'activities':
                await db_1.db.delete(schema_1.activities).where((0, drizzle_orm_1.eq)(schema_1.activities.id, id));
                break;
            case 'tasks':
                await db_1.db.delete(schema_1.tasks).where((0, drizzle_orm_1.eq)(schema_1.tasks.id, id));
                break;
            case 'notifications':
                await db_1.db.delete(schema_1.notifications).where((0, drizzle_orm_1.eq)(schema_1.notifications.id, id));
                break;
            default:
                return res.status(400).json({ error: "Invalid table name" });
        }
        res.json({ success: true, message: "Record deleted successfully" });
    }
    catch (error) {
        console.error(`Error deleting record from ${req.params.tableName}:`, error);
        res.status(500).json({ error: "Failed to delete record" });
    }
});
exports.default = router;
