import { desc, eq } from 'drizzle-orm';
import { db, schema } from 'officerdb';
import { createRouter } from '../../create-router';

export const taskLogsRouter = createRouter();

// GET / — list all logs (metadata only, no messages)
taskLogsRouter.get('/', async (ctx) => {
  const userId = ctx.get('user').id;

  const logs = await db
    .select({
      id: schema.taskLogs.id,
      taskName: schema.taskLogs.taskName,
      taskDirName: schema.taskLogs.taskDirName,
      entryName: schema.taskLogs.entryName,
      entryType: schema.taskLogs.entryType,
      provider: schema.taskLogs.provider,
      model: schema.taskLogs.model,
      isError: schema.taskLogs.isError,
      startedAt: schema.taskLogs.startedAt,
      completedAt: schema.taskLogs.completedAt,
    })
    .from(schema.taskLogs)
    .where(eq(schema.taskLogs.userId, userId))
    .orderBy(desc(schema.taskLogs.startedAt));

  return ctx.json(logs);
});

// GET /:id — return full log with messages
taskLogsRouter.get('/:id', async (ctx) => {
  const userId = ctx.get('user').id;
  const id = Number(ctx.req.param('id'));

  if (Number.isNaN(id)) {
    return ctx.text('Invalid id', 400);
  }

  const [log] = await db.select().from(schema.taskLogs).where(eq(schema.taskLogs.id, id));

  if (!log || log.userId !== userId) {
    return ctx.text('Not found', 404);
  }

  return ctx.json(log);
});
