import { http, setAccessToken, setRefreshToken } from './client';
import type { Profile, Company, UserRole } from '../types';

export interface LoginRequest {
  username: string;
  password: string;
}

export interface LoginResponse {
  access_token: string;
  refresh_token: string;
  user: Profile;
  company: Company | null;
}

export interface RegisterRequest {
  username: string;
  password: string;
  display_name: string;
  company_name: string;
  phone: string;
  role: UserRole;
}

export interface MeResponse {
  user: Profile;
  company: Company | null;
}

export const authApi = {
  login: async (data: LoginRequest) => {
    const res = await http.post<LoginResponse>('/auth/login', data);
    setAccessToken(res.data.access_token);
    setRefreshToken(res.data.refresh_token);
    return res.data;
  },

  register: (data: RegisterRequest) =>
    http.post<LoginResponse>('/auth/register', data).then(r => r.data),

  logout: async () => {
    await http.post('/auth/logout');
    setAccessToken(null);
    setRefreshToken(null);
  },

  refresh: async () => {
    const res = await http.post<{ access_token: string }>('/auth/refresh');
    setAccessToken(res.data.access_token);
    return res.data.access_token;
  },

  me: () => http.get<MeResponse>('/auth/me').then(r => r.data),
};
