package com.gzzm.lobster.thread;

import net.cyan.thunwind.annotation.OQL;
import net.cyan.thunwind.annotation.OQLUpdate;
import net.cyan.thunwind.dao.GeneralDao;

import java.util.Date;
import java.util.List;

/**
 * ThreadDao —— Thread 持久化 / Thread persistence.
 */
public abstract class ThreadDao extends GeneralDao {

    @OQL("select t from ThreadRoom t where t.threadId=:1 and t.deleteTag=0")
    public abstract ThreadRoom getThread(String threadId) throws Exception;

    @OQL("select t from ThreadRoom t where t.userId=:1 and t.deleteTag=0 order by t.lastActivityAt desc limit :2,:3")
    public abstract List<ThreadRoom> listByUser(String userId, int offset, int limit) throws Exception;

    @OQL("select count(t.threadId) from ThreadRoom t where t.userId=:1 and t.deleteTag=0")
    public abstract Long countByUser(String userId) throws Exception;

    @OQL("select t from ThreadRoom t where t.deleteTag=0 order by t.lastActivityAt desc limit :1,:2")
    public abstract List<ThreadRoom> listAll(int offset, int limit) throws Exception;

    @OQL("select count(t.threadId) from ThreadRoom t where t.deleteTag=0")
    public abstract Long countAll() throws Exception;

    @OQLUpdate("update ThreadRoom set lastActivityAt=?1, updateTime=?1 where threadId=?2")
    public abstract int touch(Date now, String threadId) throws Exception;

    @OQLUpdate("update ThreadRoom set activeRunId=?1, activeRunUpdatedAt=?2, updateTime=?2 where threadId=?3 and userId=?4 and activeRunId is null")
    public abstract int claimActiveRun(String runId, Date now, String threadId, String userId) throws Exception;

    @OQLUpdate("update ThreadRoom set activeRunId=?1, activeRunUpdatedAt=?2, updateTime=?2 where threadId=?3 and userId=?4 and activeRunId=?5")
    public abstract int replaceActiveRun(String newRunId, Date now, String threadId, String userId, String expectedRunId) throws Exception;

    @OQLUpdate("update ThreadRoom set activeRunId=null, activeRunUpdatedAt=?1, updateTime=?1 where threadId=?2 and activeRunId=?3")
    public abstract int clearActiveRunIfMatches(Date now, String threadId, String runId) throws Exception;

    @OQLUpdate("update ThreadRoom set title=?1, updateTime=?2 where threadId=?3 and userId=?4")
    public abstract int renameOwned(String title, Date now, String threadId, String userId) throws Exception;

    @OQLUpdate("update ThreadRoom set deleteTag=1, updateTime=?1 where threadId=?2 and userId=?3")
    public abstract int softDelete(Date now, String threadId, String userId) throws Exception;
}
