import { Body, Controller, Get, HttpStatus, Param, Patch, Post, Req, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AppException, ErrorCode } from '../../common/errors';
import { LabCaseAccessService } from './lab-case-access.service';
import {
  CreateLabCaseCommentDto,
  SetCommentVisibilityDto,
} from '../lab-case-comments/dto/lab-case-comment.dto';

@ApiTags('lab-cases')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@Controller('lab-cases/access')
export class LabCaseAccessController {
  constructor(private readonly accessService: LabCaseAccessService) {}

  private requireOrganizationId(req: { user?: { organizationId?: string } }): string {
    const organizationId = req.user?.organizationId;
    if (!organizationId) {
      throw new AppException(ErrorCode.AUTH_ORG_NOT_SELECTED, HttpStatus.BAD_REQUEST);
    }
    return organizationId;
  }

  @Get(':token')
  @ApiOperation({ summary: 'Resolve a lab case share link for the current user' })
  resolve(@Param('token') token: string, @Req() req) {
    return this.accessService.resolveByToken(
      token,
      req.user.id,
      this.requireOrganizationId(req),
      req.user.language,
    );
  }

  @Get(':token/tasks')
  @ApiOperation({ summary: 'List all tasks for a lab case share link' })
  listTasks(@Param('token') token: string, @Req() req) {
    return this.accessService.listTasksByToken(
      token,
      req.user.id,
      this.requireOrganizationId(req),
      req.user.language,
    );
  }

  @Get(':token/comments')
  @ApiOperation({ summary: 'List comments for a lab case share link' })
  listComments(@Param('token') token: string, @Req() req) {
    return this.accessService.listCommentsByToken(
      token,
      req.user.id,
      this.requireOrganizationId(req),
    );
  }

  @Post(':token/comments')
  @ApiOperation({ summary: 'Add a comment via a lab case share link' })
  addComment(
    @Param('token') token: string,
    @Body() dto: CreateLabCaseCommentDto,
    @Req() req,
  ) {
    return this.accessService.addCommentByToken(
      token,
      req.user.id,
      this.requireOrganizationId(req),
      dto,
    );
  }

  @Patch(':token/comments/:commentId/visibility')
  @ApiOperation({ summary: 'Toggle clinic visibility for a lab comment on a share link' })
  setCommentVisibility(
    @Param('token') token: string,
    @Param('commentId') commentId: string,
    @Body() dto: SetCommentVisibilityDto,
    @Req() req,
  ) {
    return this.accessService.setCommentVisibilityByToken(
      token,
      commentId,
      req.user.id,
      this.requireOrganizationId(req),
      dto.visibleToClinic,
    );
  }
}
