import { and, desc, eq, inArray, sql } from "drizzle-orm";
import { reminders } from "../db/schema.js";
import { uuidv7 } from "../db/uuidv7.js";
function normalizeTags(tags) {
    return JSON.stringify([
        ...new Set((tags ?? [])
            .filter((tag) => typeof tag === "string")
            .map((tag) => tag.trim().toLowerCase())
            .filter(Boolean)),
    ].slice(0, 20));
}
function normalizeLimit(limit, fallback = 100) {
    if (typeof limit !== "number" || !Number.isFinite(limit) || limit < 1)
        return fallback;
    return Math.min(Math.floor(limit), 500);
}
export class ReminderService {
    db;
    constructor(db) {
        this.db = db;
    }
    list(options = {}) {
        const conditions = [];
        if (options.userId)
            conditions.push(eq(reminders.userId, options.userId));
        if (options.status && options.status !== "all")
            conditions.push(eq(reminders.status, options.status));
        if (options.workspaceId)
            conditions.push(eq(reminders.workspaceId, options.workspaceId));
        if (options.sessionId)
            conditions.push(eq(reminders.sessionId, options.sessionId));
        let query = this.db.select().from(reminders).$dynamic();
        if (conditions.length > 0)
            query = query.where(and(...conditions));
        return query
            .orderBy(desc(reminders.updatedAt))
            .limit(normalizeLimit(options.limit))
            .all();
    }
    listByIds(ids) {
        const uniqueIds = [...new Set(ids.filter(Boolean))];
        if (uniqueIds.length === 0)
            return [];
        return this.db
            .select()
            .from(reminders)
            .where(inArray(reminders.id, uniqueIds))
            .all();
    }
    getById(id, userId) {
        return this.db
            .select()
            .from(reminders)
            .where(userId ? and(eq(reminders.id, id), eq(reminders.userId, userId)) : eq(reminders.id, id))
            .get();
    }
    create(params) {
        const content = params.content.trim();
        if (!content)
            throw new Error("Reminder content is required");
        const id = uuidv7();
        const now = new Date().toISOString();
        this.db.insert(reminders).values({
            id,
            userId: params.userId ?? null,
            workspaceId: params.workspaceId ?? null,
            sessionId: params.sessionId ?? null,
            content,
            sourceType: params.sourceType?.trim() || "agent",
            sourceId: params.sourceId?.trim() || null,
            sourceSurface: params.sourceSurface?.trim() || "chat",
            status: params.status ?? "active",
            tags: normalizeTags(params.tags),
            createdAt: now,
            updatedAt: now,
        }).run();
        return this.getById(id);
    }
    update(id, params, userId) {
        const set = {
            updatedAt: new Date().toISOString(),
        };
        if (params.content !== undefined) {
            const content = params.content.trim();
            if (!content)
                throw new Error("Reminder content must not be empty");
            set.content = content;
        }
        if (params.workspaceId !== undefined)
            set.workspaceId = params.workspaceId;
        if (params.sessionId !== undefined)
            set.sessionId = params.sessionId;
        if (params.status !== undefined)
            set.status = params.status;
        if (params.tags !== undefined)
            set.tags = normalizeTags(params.tags);
        this.db
            .update(reminders)
            .set(set)
            .where(userId ? and(eq(reminders.id, id), eq(reminders.userId, userId)) : eq(reminders.id, id))
            .run();
        return this.getById(id, userId);
    }
    delete(id, userId) {
        const existing = this.getById(id, userId);
        if (!existing)
            return false;
        this.db
            .delete(reminders)
            .where(userId ? and(eq(reminders.id, id), eq(reminders.userId, userId)) : eq(reminders.id, id))
            .run();
        return true;
    }
    countByWorkspace(userId) {
        const rows = this.db
            .select({
            workspaceId: reminders.workspaceId,
            count: sql `count(*)`,
        })
            .from(reminders)
            .where(and(eq(reminders.userId, userId), eq(reminders.status, "active")))
            .groupBy(reminders.workspaceId)
            .all();
        const counts = new Map();
        for (const row of rows) {
            if (row.workspaceId)
                counts.set(row.workspaceId, Number(row.count));
        }
        return counts;
    }
}
//# sourceMappingURL=reminders.js.map