import { Body, Delete, Param } from '@nestjs/common';
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiParam } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { NewsletterService } from '../newsletter/newsletter.service';
import { StructuresService } from '../structures/services/structures.service';
import { Roles } from '../users/decorators/roles.decorator';
import { RolesGuard } from '../users/guards/roles.guard';
import { UsersService } from '../users/users.service';
import { PendingStructureDto } from './dto/pending-structure.dto';
import { UnclaimedStructureDto } from './dto/unclaimed-structure-dto';

@Controller('admin')
export class AdminController {
  constructor(
    private usersService: UsersService,
    private structuresService: StructuresService,
    private newsletterService: NewsletterService
  ) {}

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Get('pendingStructures')
  @ApiOperation({ description: 'Get pending structre for validation' })
  public async getPendingAttachments(): Promise<PendingStructureDto[]> {
    const pendingStructure = await this.usersService.getPendingStructures();
    return await Promise.all(
      pendingStructure.map(async (structure) => {
        structure.structureName = (await this.structuresService.findOne(structure.structureId)).structureName;
        return structure;
      })
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Get('unclaimedStructures')
  @ApiOperation({ description: 'Get pending structre for validation' })
  public async getUnclaimedStructures(): Promise<UnclaimedStructureDto[]> {
    const unclaimedStructures = await this.structuresService.findAllUnclaimed();
    return unclaimedStructures;
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('validatePendingStructure')
  @ApiOperation({ description: 'Validate structure ownership' })
  public async validatePendingStructure(@Body() pendingStructureDto: PendingStructureDto) {
    const structure = await this.structuresService.findOne(pendingStructureDto.structureId);
    await this.usersService.validatePendingStructure(
      pendingStructureDto.userEmail,
      pendingStructureDto.structureId,
      structure.structureName,
      true
    );
    const pendingStructure = await this.usersService.getPendingStructures();
    return await Promise.all(
      pendingStructure.map(async (pendingStructureData) => {
        pendingStructureData.structureName = (
          await this.structuresService.findOne(pendingStructureData.structureId)
        ).structureName;
        return pendingStructureData;
      })
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('rejectPendingStructure')
  @ApiOperation({ description: 'Refuse structure ownership' })
  public async refusePendingStructure(@Body() pendingStructureDto: PendingStructureDto) {
    const structure = await this.structuresService.findOne(pendingStructureDto.structureId);
    await this.usersService.validatePendingStructure(
      pendingStructureDto.userEmail,
      pendingStructureDto.structureId,
      structure.structureName,
      false
    );
    const pendingStructure = await this.usersService.getPendingStructures();
    return await Promise.all(
      pendingStructure.map(async (pendingStructureData) => {
        pendingStructureData.structureName = (
          await this.structuresService.findOne(pendingStructureData.structureId)
        ).structureName;
        return pendingStructureData;
      })
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Delete('user/:id')
  @ApiParam({ name: 'id', type: String, required: true })
  public async deleteUser(@Param() params) {
    const user = await this.usersService.deleteOneId(params.id);
    user.structuresLink.forEach((structureId) => {
      this.usersService.isStructureClaimed(structureId.toString()).then((userFound) => {
        if (!userFound) {
          this.structuresService.deleteOne(structureId.toString());
        }
      });
    });
    return user;
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('searchUsers')
  public async searchUsers(@Body() searchString: { searchString: string }) {
    if (searchString && searchString.searchString.length > 0)
      return this.usersService.searchUsers(searchString.searchString);
    else return this.usersService.findAll();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Post('searchNewsletterSubscriptions')
  public async getNewsletterSubscriptions(@Body() searchString: { searchString: string }) {
    if (searchString && searchString.searchString.length > 0)
      return this.newsletterService.searchNewsletterSubscription(searchString.searchString);
    else return this.newsletterService.findAll();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Get('countNewsletterSubscriptions')
  public async countNewsletterSubscriptions(): Promise<number> {
    return this.newsletterService.countNewsletterSubscriptions();
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('admin')
  @Delete('newsletterSubscription/:email')
  @ApiParam({ name: 'email', type: String, required: true })
  public async unsubscribeUserFromNewsletter(@Param() params) {
    return await this.newsletterService.deleteOneEmail(params.email);
  }
}