import { eq, and, type Db, missionTasks } from '@mosaicstack/db';

export type MissionTask = typeof missionTasks.$inferSelect;
export type NewMissionTask = typeof missionTasks.$inferInsert;

export function createMissionTasksRepo(db: Db) {
  return {
    async findByMission(missionId: string): Promise<MissionTask[]> {
      return db.select().from(missionTasks).where(eq(missionTasks.missionId, missionId));
    },

    async findByMissionAndUser(missionId: string, userId: string): Promise<MissionTask[]> {
      return db
        .select()
        .from(missionTasks)
        .where(and(eq(missionTasks.missionId, missionId), eq(missionTasks.userId, userId)));
    },

    async findById(id: string): Promise<MissionTask | undefined> {
      const rows = await db.select().from(missionTasks).where(eq(missionTasks.id, id));
      return rows[0];
    },

    async findByIdAndUser(id: string, userId: string): Promise<MissionTask | undefined> {
      const rows = await db
        .select()
        .from(missionTasks)
        .where(and(eq(missionTasks.id, id), eq(missionTasks.userId, userId)));
      return rows[0];
    },

    async create(data: NewMissionTask): Promise<MissionTask> {
      const rows = await db.insert(missionTasks).values(data).returning();
      return rows[0]!;
    },

    async update(id: string, data: Partial<NewMissionTask>): Promise<MissionTask | undefined> {
      const rows = await db
        .update(missionTasks)
        .set({ ...data, updatedAt: new Date() })
        .where(eq(missionTasks.id, id))
        .returning();
      return rows[0];
    },

    async remove(id: string): Promise<boolean> {
      const rows = await db.delete(missionTasks).where(eq(missionTasks.id, id)).returning();
      return rows.length > 0;
    },

    async removeByMission(missionId: string): Promise<number> {
      const rows = await db
        .delete(missionTasks)
        .where(eq(missionTasks.missionId, missionId))
        .returning();
      return rows.length;
    },
  };
}

export type MissionTasksRepo = ReturnType<typeof createMissionTasksRepo>;
