import apiClient from '@/lib/apiClient';

export interface GenerateToken {
  client_id: string;
}

export interface GenerateTokenWithPassword extends GenerateToken {
  username: string;
  password: string;
}

export interface GenerateTokenResponse {
  access_token: string;
  expires_in: number;
  token_type: 'Bearer';
  refresh_token: string;
  scope: string;
}

export const generateTokenWithPassword = (
  request: GenerateTokenWithPassword,
) => {
  const body = new URLSearchParams();
  body.set('grant_type', 'password');
  body.set('client_id', request.client_id);
  body.set(
    'scope',
    import.meta.env.VITE_IDENTITY_SCOPE + ' ' + request.client_id,
  );
  body.set('username', request.username);
  body.set('password', request.password);

  return apiClient.post<GenerateTokenResponse>(
    import.meta.env.VITE_IDENTITY_URL,
    body.toString(),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    },
  );
};

export interface GenerateTokenWithOTP extends GenerateToken {
  email?: string;
  phonenumber?: string;
  otp: string;
}

export const generateTokenWithOtp = (request: GenerateTokenWithOTP) => {
  const body = new URLSearchParams();
  body.set('grant_type', 'otp');
  body.set('client_id', request.client_id);
  body.set(
    'scope',
    import.meta.env.VITE_IDENTITY_SCOPE + ' ' + request.client_id,
  );
  if (request.email) body.set('email', request.email);
  if (request.phonenumber) body.set('phonenumber', request.phonenumber);
  body.set('otp_code', request.otp);

  return apiClient.post<GenerateTokenResponse>(
    import.meta.env.VITE_IDENTITY_URL,
    body.toString(),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    },
  );
};

export interface GenerateTokenWithGoogle extends GenerateToken {
  idToken: string;
}

export const generateTokenWithGoogle = (request: GenerateTokenWithGoogle) => {
  const body = new URLSearchParams();
  body.set('grant_type', 'google');
  body.set('client_id', request.client_id);
  body.set(
    'scope',
    import.meta.env.VITE_IDENTITY_SCOPE + ' ' + request.client_id,
  );
  body.set('idtoken', request.idToken);

  return apiClient.post<GenerateTokenResponse>(
    import.meta.env.VITE_IDENTITY_URL,
    body.toString(),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    },
  );
};
