'use client';

import type {
  ExchangeCodeResponse,
  MockLoginRequest,
  MockLoginResponse,
  MockOrgsResponse,
  MockUsersResponse,
  RefreshTokenResponse,
  SessionResponse,
} from '@pac/types';
import { api } from './api-client';

/// 会话视图 — JWT 只装通用 orgScope(设计 B),诊所/品牌过滤维由后端展开后经此端点返回。
export async function getSession(): Promise<SessionResponse> {
  return api.get<SessionResponse>('/pac/v1/auth/session');
}

export async function exchangeCode(code: string): Promise<ExchangeCodeResponse> {
  return api.post<ExchangeCodeResponse>(
    '/pac/v1/auth/exchange-code',
    { code },
    { auth: false },
  );
}

export async function refreshToken(token: string): Promise<RefreshTokenResponse> {
  return api.post<RefreshTokenResponse>(
    '/pac/v1/auth/refresh',
    { refreshToken: token },
    { auth: false },
  );
}

/// Mock login(开发 / 试部署用)— 按 { tenant, role } 预制 user 直产 JWT
/// 生产 host SSO 接入后,后端 env PAC_ENABLE_MOCK_LOGIN=false 关闭,此调用会返 10107
export async function mockLogin(req: MockLoginRequest): Promise<MockLoginResponse> {
  return api.post<MockLoginResponse>('/pac/v1/auth/mock-login', req, { auth: false });
}

/// 客服花名册(开发 / 试部署用)— "快速登录"对话框选人;mock 关闭时 users 为空
export async function getMockUsers(): Promise<MockUsersResponse> {
  return api.get<MockUsersResponse>('/pac/v1/auth/mock-users', { auth: false });
}

/// 真实组织结构(品牌→诊所,派生自摄入数据)— 多品牌宿主快速登录选数据范围用
export async function getMockOrgs(host = 'friday'): Promise<MockOrgsResponse> {
  return api.get<MockOrgsResponse>(`/pac/v1/auth/mock-orgs?host=${encodeURIComponent(host)}`, {
    auth: false,
  });
}
