import {
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Inject,
  NotFoundException,
  Param,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../auth/auth.guard.js';
import { CurrentUser } from '../auth/current-user.decorator.js';
import { scopeFromUser, type AuthenticatedUserLike } from '../auth/session-scope.js';
import { AgentService } from './agent.service.js';

@Controller('api/sessions')
@UseGuards(AuthGuard)
export class SessionsController {
  constructor(@Inject(AgentService) private readonly agentService: AgentService) {}

  @Get()
  list(@CurrentUser() user: AuthenticatedUserLike) {
    const sessions = this.agentService.listSessions(scopeFromUser(user));
    return { sessions, total: sessions.length };
  }

  @Get(':id')
  findOne(@Param('id') id: string, @CurrentUser() user: AuthenticatedUserLike) {
    const info = this.agentService.getSessionInfo(id, scopeFromUser(user));
    if (!info) throw new NotFoundException('Session not found');
    return info;
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  async destroy(@Param('id') id: string, @CurrentUser() user: AuthenticatedUserLike) {
    const scope = scopeFromUser(user);
    const info = this.agentService.getSessionInfo(id, scope);
    if (!info) throw new NotFoundException('Session not found');
    await this.agentService.destroySession(id, scope);
  }
}
