"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const asyncHandler_1 = require("../utils/asyncHandler");
const db_1 = require("../db");
const schema_1 = require("../db/schema");
const drizzle_orm_1 = require("drizzle-orm");
const auth_1 = require("../utils/auth");
const errorHandler_1 = require("../middleware/errorHandler");
const validation_1 = require("../utils/validation");
const router = (0, express_1.Router)();
router.use(auth_1.authMiddleware);
router.get('/me', (0, asyncHandler_1.asyncHandler)(async (req, res) => {
    const userId = req.user.userId;
    const user = await db_1.db.select().from(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.id, userId)).limit(1);
    if (user.length === 0) {
        throw new errorHandler_1.AppError('NOT_FOUND', 'User not found', 404);
    }
    const settings = await db_1.db
        .select()
        .from(schema_1.userSettings)
        .where((0, drizzle_orm_1.eq)(schema_1.userSettings.userId, userId))
        .limit(1);
    let defaultCategory = settings[0]?.defaultCategory;
    if (defaultCategory) {
        const cat = await db_1.db
            .select()
            .from(schema_1.categories)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_1.categories.id, defaultCategory), (0, drizzle_orm_1.eq)(schema_1.categories.userId, userId)))
            .limit(1);
        if (cat.length === 0) {
            defaultCategory = null;
        }
    }
    res.json({
        id: user[0].id,
        username: user[0].username,
        settings: {
            darkMode: settings[0]?.darkMode ?? false,
            notifications: settings[0]?.notifications ?? true,
            reminderTime: settings[0]?.reminderTime ?? '09:00',
            defaultCategory,
            sortBy: settings[0]?.sortBy ?? 'dueDate',
            sortOrder: settings[0]?.sortOrder ?? 'asc',
        },
        createdAt: user[0].createdAt,
    });
}));
router.patch('/me/settings', (0, asyncHandler_1.asyncHandler)(async (req, res) => {
    const data = validation_1.userSettingsSchema.parse(req.body);
    const userId = req.user.userId;
    // Validate defaultCategory if provided
    if (data.defaultCategory) {
        const cat = await db_1.db
            .select()
            .from(schema_1.categories)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_1.categories.id, data.defaultCategory), (0, drizzle_orm_1.eq)(schema_1.categories.userId, userId)))
            .limit(1);
        if (cat.length === 0) {
            throw new errorHandler_1.AppError('NOT_FOUND', 'Default category not found', 404);
        }
    }
    const now = Date.now();
    const existing = await db_1.db
        .select()
        .from(schema_1.userSettings)
        .where((0, drizzle_orm_1.eq)(schema_1.userSettings.userId, userId))
        .limit(1);
    if (existing.length === 0) {
        await db_1.db.insert(schema_1.userSettings).values({
            userId,
            ...data,
            updatedAt: now,
        });
    }
    else {
        await db_1.db
            .update(schema_1.userSettings)
            .set({ ...data, updatedAt: now })
            .where((0, drizzle_orm_1.eq)(schema_1.userSettings.userId, userId));
    }
    res.status(200).json({ success: true });
}));
router.get('/search', (0, asyncHandler_1.asyncHandler)(async (req, res) => {
    const { q } = req.query;
    const userId = req.user.userId;
    if (!q || typeof q !== 'string' || q.length < 2) {
        return res.json([]);
    }
    const results = await db_1.db
        .select({ id: schema_1.users.id, username: schema_1.users.username })
        .from(schema_1.users)
        .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.ilike)(schema_1.users.username, `%${q}%`), (0, drizzle_orm_1.eq)(schema_1.users.id, userId)))
        .limit(10);
    res.json(results);
}));
exports.default = router;
//# sourceMappingURL=users.js.map