import { BadRequestException } from '@nestjs/common';
import { MemberService } from './member.service';

describe('MemberService domain writes', () => {
  const makeService = () => {
    const prisma = {
      user: {
        create: jest.fn(),
        delete: jest.fn(),
        findMany: jest.fn(),
        update: jest.fn(),
      },
    };
    return { prisma, service: new MemberService(prisma as any) };
  };

  it('creates members with UI role and department fields in users', async () => {
    const { prisma, service } = makeService();
    prisma.user.create.mockResolvedValue({
      id: 'member-1',
      name: '张三',
      username: 'zhangsan',
      departmentId: 'dept-2',
      roleId: 'role-dev',
      phone: '13000000000',
      email: 'zhangsan@example.com',
      password: 'Ftb12345',
      isSystem: false,
      createdAt: new Date('2026-07-08T00:00:00.000Z'),
    });

    await service.create({
      name: '张三',
      username: 'zhangsan',
      departmentId: 'dept-2',
      roleId: 'role-dev',
      phone: '13000000000',
      email: 'zhangsan@example.com',
      password: 'Ftb12345',
    });

    expect(prisma.user.create).toHaveBeenCalledWith({
      data: expect.objectContaining({
        name: '张三',
        username: 'zhangsan',
        departmentId: 'dept-2',
        roleId: 'role-dev',
        phone: '13000000000',
        email: 'zhangsan@example.com',
        password: 'Ftb12345',
      }),
    });
  });

  it('protects the built-in admin from deletion and privileged field edits', async () => {
    const { prisma, service } = makeService();
    prisma.user.update.mockResolvedValue({
      id: 'm-8',
      name: '超级管理员',
      username: 'admin',
      roleId: 'role-admin',
      departmentId: '',
      phone: '13200132009',
      email: 'admin@example.com',
      password: 'Ftb12345',
      isSystem: true,
      createdAt: new Date('2026-07-08T00:00:00.000Z'),
    });

    await expect(service.remove('m-8')).rejects.toBeInstanceOf(BadRequestException);

    await service.update('m-8', {
      name: '误改',
      username: 'other',
      roleId: 'role-viewer',
      departmentId: 'dept-1',
      phone: '13200132009',
    });

    expect(prisma.user.delete).not.toHaveBeenCalled();
    expect(prisma.user.update).toHaveBeenCalledWith({
      where: { id: 'm-8' },
      data: expect.not.objectContaining({
        name: '误改',
        username: 'other',
        roleId: 'role-viewer',
        departmentId: 'dept-1',
      }),
    });
    expect(prisma.user.update).toHaveBeenCalledWith(expect.objectContaining({
      data: expect.objectContaining({ phone: '13200132009', isSystem: true }),
    }));
  });
});
