import axios, { AxiosInstance } from 'axios'
import { Agent as HttpsAgent } from 'node:https'

export const ADMIN_BASE = process.env.E2E_ADMIN_URL ?? 'https://admin.food-market.kz'

const httpsAgent = new HttpsAgent({ rejectUnauthorized: false })

export interface AuthSession {
  accessToken: string
  refreshToken?: string
  email: string
  roles: string[]
  orgId: string | null
}

export function makeClient(token?: string): AxiosInstance {
  return axios.create({
    baseURL: ADMIN_BASE,
    httpsAgent,
    headers: token ? { Authorization: `Bearer ${token}` } : {},
    validateStatus: () => true,  // не кидать на 4xx — runner сам решает
  })
}

export async function login(email: string, password: string): Promise<AuthSession> {
  const body = new URLSearchParams({
    grant_type: 'password',
    username: email,
    password,
    client_id: 'food-market-web',
    scope: 'openid profile email roles api offline_access',
  })
  const res = await makeClient().post('/connect/token', body, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  })
  if (res.status !== 200) {
    throw new Error(`login failed for ${email}: ${res.status} ${JSON.stringify(res.data)}`)
  }
  const tok = res.data
  const me = await makeClient(tok.access_token).get('/api/me')
  if (me.status !== 200) {
    throw new Error(`/api/me after login failed: ${me.status} ${JSON.stringify(me.data)}`)
  }
  return {
    accessToken: tok.access_token,
    refreshToken: tok.refresh_token,
    email: me.data.email,
    roles: me.data.roles ?? [],
    orgId: me.data.orgId ?? null,
  }
}
