import useSWR from 'swr';
import { fetcher } from '../hooks/fetcher';
import { User } from '@prisma/client';
import { PaginatedResponse } from '../types/api';
import { setCookie } from 'cookies-next';

export class UserService {
  static async updatePassword(token: string, password: string) {
    return await fetch(`/api/auth/reset/${token}`, {
      method: 'PATCH',
      body: JSON.stringify({ password }),
    });
  }

  static async unlinkVercel(userId: string) {
    return await fetch(`/api/users/${userId}`, {
      method: 'PATCH',
      body: JSON.stringify({ vercelAccessToken: null }),
    });
  }

  static async promoteUser(userId: string) {
    return await fetch(`/api/users/${userId}`, {
      method: 'PATCH',
      body: JSON.stringify({ role: 'ADMIN' }),
    });
  }

  static async deleteUser(userId: string) {
    return await fetch(`/api/users/${userId}`, {
      method: 'DELETE',
    });
  }

  static connectToVercel() {
    const array = new Uint8Array(32);
    window.crypto.getRandomValues(array);
    const csrfToken = Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');

    setCookie('csrf', csrfToken, {
      path: '/',
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
    });

    const integrationUrl = new URL(process.env.NEXT_PUBLIC_INTEGRATION_URL ?? '');
    integrationUrl.searchParams.set('state', csrfToken);
    window.open(integrationUrl.toString(), '_self');
  };
}

export const useUsers = (searchQuery = '', page = 1) => {
  const { data, error, isLoading, mutate } = useSWR<PaginatedResponse<User[]>>(
    `/api/users?search=${searchQuery}&page=${page}`,
    fetcher
  );
  return { users: data?.data ?? [], isLoading, error, mutate, pagination: data?.pagination };
};

export const useUser = (userId: string) => {
  const { data, error, isLoading, mutate } = useSWR(`/api/users/${userId}`, fetcher);
  return { user: data?.data ?? null, isLoading, error, mutate };
};
