/**
 * Vue.js CSRF Mixin
 * Provides CSRF token management methods to Vue components
 * 
 * Usage in Vue component:
 * import csrfMixin from './mixins/csrf-mixin.js';
 * 
 * export default {
 *   mixins: [csrfMixin],
 *   methods: {
 *     async someMethod() {
 *       const response = await this.$csrf.post('/api/endpoint', { data: 'value' });
 *     }
 *   }
 * }
 */

export default {
  created() {
    // Ensure CSRFManager is available
    if (typeof window.CSRFManager === 'undefined') {
      console.warn('[CSRF Mixin] CSRFManager not found. Make sure csrf-manager.js is loaded.');
    }
  },
  
  methods: {
    /**
     * Get current CSRF token
     * @returns {string|null}
     */
    $csrfToken() {
      return window.CSRFManager ? window.CSRFManager.getToken() : null;
    },

    /**
     * Refresh CSRF token
     * @returns {Promise<string|null>}
     */
    async $refreshCsrfToken() {
      return window.CSRFManager ? await window.CSRFManager.refreshToken() : null;
    },

    /**
     * Add CSRF token to headers
     * @param {Object} headers 
     * @returns {Object}
     */
    $addCsrfToHeaders(headers = {}) {
      return window.CSRFManager ? window.CSRFManager.addTokenToHeaders(headers) : headers;
    },

    /**
     * Enhanced fetch with CSRF handling
     * @param {string} url 
     * @param {Object} options 
     * @returns {Promise<Response>}
     */
    async $csrfFetch(url, options = {}) {
      if (window.CSRFManager) {
        return await window.CSRFManager.handleRequest(url, options);
      } else {
        // Fallback to regular fetch with manual CSRF token
        const token = this.$csrfToken();
        if (token && (options.method || 'GET').toUpperCase() !== 'GET') {
          options.headers = options.headers || {};
          options.headers['X-CSRF-TOKEN'] = token;
        }
        return await fetch(url, options);
      }
    }
  },

  // Provide convenient shorthand methods
  computed: {
    $csrf() {
      const self = this;
      return {
        token: () => self.$csrfToken(),
        refresh: () => self.$refreshCsrfToken(),
        addToHeaders: (headers) => self.$addCsrfToHeaders(headers),
        
        // HTTP method shortcuts
        get: (url, headers = {}) => self.$csrfFetch(url, { 
          method: 'GET', 
          headers: self.$addCsrfToHeaders(headers)
        }),
        
        post: (url, data, headers = {}) => self.$csrfFetch(url, {
          method: 'POST',
          headers: self.$addCsrfToHeaders({ 'Content-Type': 'application/json', ...headers }),
          body: typeof data === 'string' ? data : JSON.stringify(data)
        }),
        
        put: (url, data, headers = {}) => self.$csrfFetch(url, {
          method: 'PUT',
          headers: self.$addCsrfToHeaders({ 'Content-Type': 'application/json', ...headers }),
          body: typeof data === 'string' ? data : JSON.stringify(data)
        }),
        
        delete: (url, headers = {}) => self.$csrfFetch(url, {
          method: 'DELETE',
          headers: self.$addCsrfToHeaders(headers)
        }),
        
        patch: (url, data, headers = {}) => self.$csrfFetch(url, {
          method: 'PATCH',
          headers: self.$addCsrfToHeaders({ 'Content-Type': 'application/json', ...headers }),
          body: typeof data === 'string' ? data : JSON.stringify(data)
        })
      };
    }
  }
};