import { User } from "@/model/User";
import { setItemAsync } from "expo-secure-store";
import { AbstractService as AbstractAPIService } from "../abstract.service";
import { IUserService } from "./user.service.interface";

export class UserAPIService extends AbstractAPIService implements IUserService {
  async login(email: string, password: string): Promise<User> {
    const body = new URLSearchParams({
      grant_type: "password",
      client_id: email,
      client_secret: this.CLIENT_SECRET,
      email,
      password,
      scope: this.SCOPES,
    });

    const res = await fetch(`${this.IDP_URL}/connect/token`, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: body.toString(),
    });

    if (!res.ok) throw new Error(`Auth failed: ${res.status}`);
    const json = await res.json();

    await setItemAsync(this.ACCESS_TOKEN_PATH, json.access_token);
    await setItemAsync(this.REFRESH_TOKEN_PATH, json.refresh_token);

    return json;
  }
}
