import {
  Body,
  Controller,
  Get,
  NotFoundException,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
} from '@nestjs/common';
import {
  InvitationCreateSchema,
  UserUpdateSchema,
  type InvitationCreate,
  type MeResponse,
  type RoleName,
  type UserUpdate,
} from '@siop/shared';
import {
  AuthenticatedUser,
  CurrentUser,
} from '../auth/current-user.decorator';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { PermissionsService } from '../permissions/permissions.service';
import { RequirePermission } from '../permissions/require-permission.decorator';
import { PrismaService } from '../prisma/prisma.service';
import { UsersService } from './users.service';

@Controller()
export class UsersController {
  constructor(
    private readonly prisma: PrismaService,
    private readonly permissionsService: PermissionsService,
    private readonly usersService: UsersService,
  ) {}

  /** Profil courant — pas de permission : chacun lit le sien. */
  @Get('users/me')
  async me(@CurrentUser() current: AuthenticatedUser): Promise<MeResponse> {
    const user = await this.prisma.user.findUnique({
      where: { id: current.userId },
      include: { role: true },
    });
    if (!user || !user.isActive) throw new NotFoundException();
    return {
      id: user.id,
      email: user.email,
      displayName: user.displayName,
      role: { id: user.role.id, name: user.role.name as RoleName },
      isDemo: user.isDemo,
      permissions: await this.permissionsService.getForRole(user.roleId),
    };
  }

  @Get('users')
  @RequirePermission('PEOPLE_TEAMS', 'view')
  list() {
    return this.usersService.list();
  }

  @Get('roles')
  @RequirePermission('PEOPLE_TEAMS', 'view')
  roles() {
    return this.usersService.roles();
  }

  @Post('users/invitations')
  @RequirePermission('PEOPLE_TEAMS', 'create')
  invite(@Body(new ZodValidationPipe(InvitationCreateSchema)) body: InvitationCreate) {
    return this.usersService.invite(body);
  }

  @Post('users/:id/invitation')
  @RequirePermission('PEOPLE_TEAMS', 'edit')
  resendInvitation(@Param('id', ParseUUIDPipe) id: string) {
    return this.usersService.resendInvitation(id);
  }

  @Patch('users/:id')
  @RequirePermission('PEOPLE_TEAMS', 'edit')
  update(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(UserUpdateSchema)) body: UserUpdate,
  ) {
    return this.usersService.update(id, body);
  }
}
