"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const db_1 = require("../db");
const schema_1 = require("../db/schema");
const drizzle_orm_1 = require("drizzle-orm");
const auth_1 = require("../middleware/auth");
const crypto_1 = __importDefault(require("crypto"));
const router = (0, express_1.Router)();
// Get targets for a user
router.get("/:userId", auth_1.authenticateToken, async (req, res) => {
    try {
        const targets = await db_1.db.select()
            .from(schema_1.monthlyTargets)
            .where((0, drizzle_orm_1.eq)(schema_1.monthlyTargets.userId, req.params.userId));
        res.json(targets);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
// Update or create target for a specific month
router.post("/", auth_1.authenticateToken, async (req, res) => {
    try {
        const { userId, month, targetAmount } = req.body;
        // Only admins can set targets
        if (req.user.role !== 'admin' && req.user.role !== 'sales-manager') {
            return res.status(403).json({ error: "Unauthorized" });
        }
        if (!userId || !month || targetAmount === undefined) {
            return res.status(400).json({ error: "Missing required fields" });
        }
        // Check if target for this month already exists
        const existing = await db_1.db.select()
            .from(schema_1.monthlyTargets)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_1.monthlyTargets.userId, userId), (0, drizzle_orm_1.eq)(schema_1.monthlyTargets.month, month)));
        if (existing.length > 0) {
            // Update
            await db_1.db.update(schema_1.monthlyTargets)
                .set({ targetAmount })
                .where((0, drizzle_orm_1.eq)(schema_1.monthlyTargets.id, existing[0].id));
            res.json({ message: "Target updated", id: existing[0].id });
        }
        else {
            // Create
            const id = crypto_1.default.randomUUID();
            await db_1.db.insert(schema_1.monthlyTargets).values({
                id,
                userId,
                month,
                targetAmount
            });
            res.json({ message: "Target created", id });
        }
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
exports.default = router;
