import PocketBase from 'pocketbase';

export interface LoginResponse {
  record: {
    avatar: string;
    email: string;
    emailVisibility: false;
    id: string;
    name: string;
    verified: false;
  };
  token: string;
  status: number;
}

export const login = async (
  email: string,
  password: string
): Promise<LoginResponse> => {
  const pb = new PocketBase(import.meta.env.VITE_BASE_URL_API);
  const collection = 'users';

  try {
    const authData = await pb
      .collection(collection)
      .authWithPassword(email, password);

    return {
      record: {
        avatar: authData.record.avatar,
        email: authData.record.email,
        emailVisibility: authData.record.emailVisibility,
        id: authData.record.id,
        name: authData.record.name,
        verified: authData.record.verified,
      },
      token: authData.token,
      status: 200,
    };
  } catch (error) {
    const err = error as { status: number };
    return {
      record: {
        avatar: '',
        email: '',
        emailVisibility: false,
        id: '',
        name: '',
        verified: false,
      },
      token: '',
      status: err.status,
    };
  }
};
