import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Req,
  UseGuards,
} from '@nestjs/common';
import { AdminsService } from '../services/admins.service';
import { Paginate, PaginateQuery } from 'nestjs-paginate';
import Admin from '../entities/admin.entity';
import { UpdateDto } from '../dtos/update.dto';
import { DeletesDto } from '../dtos/deletes.dto';
import { Request } from 'express';
import { CreateDto } from '../dtos/create.dto';
import Permission from '../entities/permission.entity';
import { GrantNewPasswordDto } from '../dtos/grant-new-password.dto';
import { SystemAccountGuard } from '@/system/guards/system-account.guard';

@Controller('admin/admins')
export class AdminsController {
  constructor(private readonly adminService: AdminsService) {}

  @Get()
  async index(@Paginate() query: PaginateQuery) {
    return await this.adminService.index(query);
  }

  @Delete(':id')
  async delete(@Param('id') id: Admin['id']) {
    return await this.adminService.delete(id);
  }

  @Put(':id')
  async update(@Param('id') id: Admin['id'], @Body() data: UpdateDto) {
    const permissions = data.permissions
      ? data.permissions.map((item) => {
          const permission = new Permission();
          permission.id = item.id;
          permission.name = item.name;
          return permission;
        })
      : undefined;
    return await this.adminService.update(id, { ...data, permissions });
  }

  @Post('')
  async create(@Body() data: CreateDto) {
    return await this.adminService.create(data);
  }

  @Post('grant-new-password/:id')
  @UseGuards(SystemAccountGuard)
  async grantNewPassword(
    @Param('id') id: Admin['id'],
    @Body() data: GrantNewPasswordDto,
    @Req() request: Request,
  ) {
    return await this.adminService.grantNewPassword(id, data.password, request);
  }

  @Post('deletes')
  async deletes(@Body() data: DeletesDto, @Req() request: Request) {
    return await this.adminService.deletes(data.ids, request);
  }
}
