import request from 'supertest';
import { Role } from '../../../src/generated/prisma/enums.js';
import { expectSuccessEnvelope } from './e2e-http.helper.js';

/**
 * 生成 E2E 用的小程序模拟授权参数。
 */
export function buildMiniAppMockPayload(phone: string, openId: string) {
  return {
    loginCode: `mock-login:${encodeURIComponent(openId)}`,
    phoneCode: `mock-phone:${phone}`,
  };
}

/**
 * 通过 B 端小程序登录接口获取院内账号 token。
 */
export async function loginByMiniApp(
  server: request.SuperTest<request.Test>,
  options: {
    phone: string;
    openId: string;
    role?: Role;
    hospitalId?: number;
    userId?: number;
  },
) {
  const response = await request(server)
    .post('/auth/miniapp/b/phone-login')
    .send(buildMiniAppMockPayload(options.phone, options.openId));

  expectSuccessEnvelope(response, 201);
  const firstStage = response.body.data as
    | {
        accessToken: string;
      }
    | {
        needSelect: true;
        loginTicket: string;
        accounts: Array<{
          id: number;
          role: Role;
          hospitalId: number | null;
        }>;
      };

  if ('accessToken' in firstStage) {
    return firstStage.accessToken;
  }

  const selectedAccount = firstStage.accounts.find((account) => {
    if (options.userId != null) {
      return account.id === options.userId;
    }

    if (options.role == null) {
      return false;
    }

    return (
      account.role === options.role &&
      (options.hospitalId == null || account.hospitalId === options.hospitalId)
    );
  });

  expect(selectedAccount).toBeTruthy();

  const confirmResponse = await request(server)
    .post('/auth/miniapp/b/phone-login/confirm')
    .send({
      loginTicket: firstStage.loginTicket,
      userId: selectedAccount?.id,
    });

  expectSuccessEnvelope(confirmResponse, 201);
  return confirmResponse.body.data.accessToken as string;
}
