// SPDX-FileCopyrightText: WTF Kooperative eG <https://wtf-eg.de/>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

export default {
  methods: {
    async submitLogin() {
      this.showErrorMessage = false;
      try {
        const data = JSON.stringify({
          username: this.username,
          password: this.password,
        })

        const response = await fetch(`${this.apiUrl}/users/login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: data
        })

        if (!response.ok) {
          this.showErrorMessage = true
          return
        }

        const responseData = await response.json()
        localStorage.setItem('token', responseData.token);
        localStorage.setItem('user_id', responseData.user_id);
        this.$router.push({ path: '/s/search' });
      } catch (error) {
        console.error(error);
        this.showErrorMessage = true;
      }
    },
    async search() {
      try {
        const response = await fetch(`${this.apiUrl}/${this.type}s?search=${this.searchText}`, {
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
          }
        );

        if (!response.ok) {
          console.error();
          this.showErrorMessage = true;
          return
        }

        const responseData = await response.json()
        this.searchResults = responseData[`${this.type}s`];

        if (
          !this.values
          .map((item) => item[this.type].name.toLowerCase())
          .includes(this.searchText.toLowerCase())
        ) {
          this.searchResults.unshift({ name: this.searchText });
        }
      } catch (error) {
        console.error();
        this.showErrorMessage = true;
      }
    },
    async initEditPage() {
      const userId = localStorage.getItem('user_id')
      const url = `${this.apiUrl}/users/${userId}/profile`

      try {
        const response = await fetch(url, {
            headers: { 
              Authorization: `Bearer ${localStorage.getItem("token")}` 
            },
          }
        );

        if (!response.ok) {
          return
        }

        const responseData = await response.json()
        
        this.profile = responseData.profile;
      } catch (error) {
        console.error(error);
      }
    },
    async submitFormEdit() {
      this.showErrorMessage = false
      this.showSuccessMessage = false

      try {
        const body = JSON.stringify(this.profile)
        const response = await fetch(
          `${this.apiUrl}/users/${localStorage.getItem("user_id")}/profile`,
          {
            method: 'POST',
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
              'Content-Type': 'application/json',
            },
            body
          }
        );

        if (!response.ok) {
          this.showErrorMessage = true
          return
        }
        
        this.showSuccessMessage = true
      } catch (error) {
        console.error(error);
        this.showErrorMessage = true;
      }
    },
    async initViewPage() {
      try {
        const response = await fetch(`${this.apiUrl}/users/${this.$route.params.memberId}/profile`, {
            headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
          }
        );

        if (!response.ok) {
          return
        }

        const responseData = await response.json()
        this.profile = responseData.profile;
      } catch (error) {
        console.error(error);
      }
    },
    async submitSearch() {
      this.showErrorMessage = false;

      try {
        const url = new URL(`${this.apiUrl}/users/profiles`)

        if (this.searchText != "") {
          url.searchParams.append('nickname', this.searchText)
        }

        const response = await fetch(url, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });

        if (!response.ok) {
          this.showErrorMessage = true
          return
        }

        const responseData = await response.json()

        this.searchResults = responseData.profiles;
        this.searchTotal = responseData.total;
      } catch (error) {
        console.error(error);
        this.showErrorMessage = true;
      }
    },
  },
}
