-- Smart Notification Reminder System
-- Tracks which reminders have been sent to prevent duplicates

CREATE TABLE task_reminderlog (
    id SERIAL PRIMARY KEY,
    task_id INTEGER NOT NULL REFERENCES task_task(id) ON DELETE CASCADE,
    user_id INTEGER NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
    due_date DATE NOT NULL,                              -- Which occurrence this is for
    reminder_stage VARCHAR(20) NOT NULL,                 -- e.g., "reminder_30d", "reminder_7d", "day_of", "overdue_1", "overdue_4"
    sent_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    notification_id INTEGER REFERENCES notifications_notification(id) ON DELETE SET NULL,

    -- Prevent duplicate reminders for same task/user/date/stage
    UNIQUE(task_id, user_id, due_date, reminder_stage)
);

-- Index for quick lookup when checking if reminder was already sent
CREATE INDEX idx_reminderlog_task_user_date ON task_reminderlog(task_id, user_id, due_date);

-- Index for cleanup job (delete old logs)
CREATE INDEX idx_reminderlog_sent_at ON task_reminderlog(sent_at);

COMMENT ON TABLE task_reminderlog IS 'Tracks sent task reminders to prevent duplicate notifications';
COMMENT ON COLUMN task_reminderlog.reminder_stage IS 'Stage of reminder: reminder_30d, reminder_14d, reminder_7d, reminder_3d, reminder_1d, day_of, overdue_N';
