import {
  ACAttrFilter,
  ACGuard,
  ApiPaginatedResponse,
  diskStorage,
  PageDto,
  PageMetaDto,
  PageOptionsDto,
  pick,
  UserType,
} from '@gadmin2n/nest-common';
import {
  Body,
  Controller,
  Delete,
  Inject,
  NotFoundException,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Req,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import {
  ApiCreatedResponse,
  ApiNotFoundResponse,
  ApiOkResponse,
  ApiTags,
} from '@nestjs/swagger';
import { Prisma } from '@prisma/client';
import { UseRoles } from 'nest-access-control';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { CreateRoleDto } from '../../generated/role/dto/create-role.dto';
import {
  EffectedCount,
  RoleFindManyArgs,
  RoleWhereSelect,
  UploudResponse,
} from '../../generated/role/dto/role-types.dto';
import { UpdateRoleDto } from '../../generated/role/dto/update-role.dto';
import { RoleEntity } from '../../generated/role/entities/role.entity';
import { RoleService } from './role.service';

import { ConfigService } from '@nestjs/config';
import { FileInterceptor } from '@nestjs/platform-express';
import { Type } from 'class-transformer';
import { IsArray, IsOptional } from 'class-validator';

// 自定义控制器层输入类型,扩展 pageIds 字段
export class UpdateRoleWithPagesDto extends UpdateRoleDto {
  @IsOptional()
  @IsArray()
  @Type(() => Number)
  pageIds?: number[];
}

export class CreateRoleWithPagesDto extends CreateRoleDto {
  @IsOptional()
  @IsArray()
  @Type(() => Number)
  pageIds?: number[];
}

@UseGuards(ACGuard)
@Controller('role')
@ApiTags('role')
export class RoleController {
  constructor(
    private readonly roleService: RoleService,
    private readonly config: ConfigService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  @Post('createOne')
  @UseRoles({
    resource: 'role',
    action: 'create',
    possession: 'any',
  })
  @ApiCreatedResponse({ type: RoleEntity })
  async createOne(
    @Body() body: CreateRoleWithPagesDto,
    @ACAttrFilter() acAttrFilter,
    @Req() request: Request & { user: UserType },
  ) {
    body.creator = request.user.username;
    const { pageIds, ...roleData } = body;

    // 使用 Prisma 事务创建角色及其页面权限
    const role = await this.roleService.createRoleWithPages(
      acAttrFilter(roleData),
      pageIds,
    );

    return new RoleEntity(acAttrFilter(role));
  }

  @Post('findMany')
  @UseRoles({
    resource: 'role',
    action: 'read',
    possession: 'any',
  })
  @ApiPaginatedResponse(RoleEntity)
  async findMany(
    @Body() body: RoleFindManyArgs,
    @ACAttrFilter() acAttrFilter,
  ): Promise<PageDto<RoleEntity>> {
    const { itemCount, entities } = await this.roleService.findMany(
      body as Prisma.RoleFindManyArgs,
    );
    const { skip = 0, take = 10 } = body as Prisma.RoleFindManyArgs;
    const pageOptionsDto: PageOptionsDto = { skip, take };
    const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto });

    return new PageDto(
      entities.map((item) => new RoleEntity(acAttrFilter(item))),
      pageMetaDto,
    );
  }

  @Post('/findUnique/:id')
  @UseRoles({
    resource: 'role',
    action: 'read',
    possession: 'any',
  })
  @ApiOkResponse({ type: RoleEntity })
  @ApiNotFoundResponse({ description: 'Cannot found this record.' })
  async findUnique(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: RoleWhereSelect,
    @ACAttrFilter() acAttrFilter,
  ) {
    const item = await this.roleService.findUnique(id, body);
    if (!item) {
      throw new NotFoundException();
    }
    return new RoleEntity(acAttrFilter(item));
  }

  @Patch('updateUnique/:id')
  @UseRoles({
    resource: 'role',
    action: 'update',
    possession: 'any',
  })
  @ApiOkResponse({ type: RoleEntity })
  @ApiNotFoundResponse({ description: 'Cannot found this record.' })
  async updateUnique(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: UpdateRoleWithPagesDto,
    @ACAttrFilter() acAttrFilter,
  ) {
    const { pageIds, ...roleData } = body;

    // 删除 createdAt 字段，防止被更新
    delete (roleData as any).createdAt;

    // 使用 Prisma 事务确保原子性
    const item = await this.roleService.updateRoleWithPages(
      id,
      acAttrFilter(roleData),
      pageIds,
    );

    return new RoleEntity(acAttrFilter(item));
  }

  @Delete('deleteUnique/:id')
  @UseRoles({
    resource: 'role',
    action: 'delete',
    possession: 'any',
  })
  @ApiOkResponse({ type: EffectedCount })
  @ApiNotFoundResponse({ description: 'Cannot found this record.' })
  async deleteUnique(@Param('id', ParseIntPipe) id: number) {
    const res = await this.roleService.deleteUnique(id);
    if (!res.count) {
      throw new NotFoundException();
    }
    return res;
  }

  @Post('upload')
  @UseRoles({
    resource: 'role',
    action: 'create',
    possession: 'any',
  })
  @ApiCreatedResponse({ type: UploudResponse })
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    const fileName = await diskStorage(
      file,
      this.config.get('media')['rootDir'] + '/role/',
    );

    return {
      ...pick(file, ['mimetype', 'originalname', 'size']),
      url: this.config.get('media')['address'] + '/role/' + fileName,
      name: fileName,
    };
  }
}
