import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Inject, ILogger, Post } from '@midwayjs/core';
import { NotificationUserEntity } from '../../entity/user';
import { NotificationService } from '../../service/notify';

@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: NotificationUserEntity,
  pageQueryOp: {
    keyWordLikeFields: [
      'a.bizUserId',
      'a.externalUserId',
      'a.openId',
      'a.name',
    ],
    fieldEq: ['a.platform', 'a.status'],
  },
})
export class AdminNotificationUserController extends BaseController {
  @Inject()
  notificationService: NotificationService;

  @Inject()
  logger: ILogger;

  @Post('/syncFeishuAll', { summary: '从飞书根部门递归同步用户' })
  async syncFeishuAll(
    @Body('rootDepartmentId') rootDepartmentId?: string,
    @Body('departmentIdType')
    departmentIdType?: 'department_id' | 'open_department_id',
    @Body('userIdType') userIdType?: 'open_id' | 'union_id' | 'user_id'
  ) {
    try {
      this.logger.info(
        `[Notification][Admin] syncFeishuAll??: rootDepartmentId=${
          rootDepartmentId || '0'
        }, departmentIdType=${
          departmentIdType || 'department_id'
        }, userIdType=${userIdType || 'open_id'}`
      );
      const result = await this.notificationService.syncFeishuUsersFromRoot({
        rootDepartmentId: rootDepartmentId || '0',
        departmentIdType: departmentIdType || 'department_id',
        userIdType: userIdType || 'open_id',
      });
      this.logger.info(
        `[Notification][Admin] syncFeishuAll??: departmentCount=${result.departmentCount}, userCount=${result.userCount}, created=${result.createdCount}, updated=${result.updatedCount}`
      );
      return this.ok(result);
    } catch (e) {
      this.logger.error(
        `[Notification][Admin] syncFeishuAll??: ${e.message}`,
        e
      );
      return this.fail(
        typeof e?.response === 'object'
          ? JSON.stringify({
              message: e.message,
              code: e.code,
              status: e.status,
              response: e.response,
            })
          : e.message
      );
    }
  }
}
