import 'reflect-metadata';
import { PERMISSION_KEY } from '../auth/decorators/permission.decorator';
import { OrganizationsController } from './organizations.controller';

describe('OrganizationsController permissions', () => {
  it('allows student editors to use the options endpoint without full entity exposure', () => {
    expect(
      Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findOptions),
    ).toEqual(['organization:view', 'student:create', 'student:edit']);
  });

  it('keeps the full entity list restricted to organization viewers only', () => {
    expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findAll)).toEqual([
      'organization:view',
    ]);
  });

  it('keeps organization detail restricted to organization viewers', () => {
    expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findOne)).toEqual([
      'organization:view',
    ]);
  });
});

describe('OrganizationsController', () => {
  it('requires organization:purge on permanent delete route', () => {
    expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.purge)).toEqual([
      'organization:purge',
    ]);
  });

  it('writes permanent delete audit logs', async () => {
    const service = {
      purge: jest.fn().mockResolvedValue({ message: '已永久删除机构（不可恢复）' }),
    };
    const log = jest.fn().mockResolvedValue(undefined);
    const controller = new OrganizationsController(service as never, { log } as never);
    const req = { user: { id: 1, username: 'admin' }, ip: '127.0.0.1', headers: {} };
    await controller.purge('1', req);
    expect(service.purge).toHaveBeenCalledWith(1);
    expect(log).toHaveBeenCalledWith(
      expect.objectContaining({ module: '机构管理', action: '永久删除机构', targetId: 1 }),
    );
  });
});
