import api, { unwrap } from './request';

export interface LoginReq {
  loginId: string;
  password: string;
}

export interface LoginResp {
  accessToken: string;
  refreshToken: string;
  user?: {
    userId: number;
    loginId: string;
    userName?: string;
    agentId?: number;
    roles?: string[];
  };
}

export interface MeResp {
  userId: number;
  loginId: string;
  userName?: string;
  email?: string;
  phone?: string;
  agentId?: number;
  agentName?: string;
  orgName?: string;
  status?: string;
  roleCodes?: string[];
  roleNames?: string[];
}

export const authApi = {
  login: (req: LoginReq) =>
    unwrap<LoginResp>(api.post('/api/auth/login', req)),
  me: () => unwrap<MeResp>(api.get('/api/auth/me')),
  refresh: (refreshToken: string) =>
    unwrap<LoginResp>(api.post('/api/auth/refresh', { refreshToken })),
  changePassword: (oldPassword: string, newPassword: string) =>
    unwrap<void>(api.post('/api/auth/password', { oldPassword, newPassword })),
  updateMyPhone: (phone: string) =>
    unwrap<void>(api.put('/api/mobile/me/profile/phone', { phone })),
  logout: () => api.post('/api/auth/logout').catch(() => undefined),
};
