const SUPABASE_URL = 'https://hwithddwaapyhnfwcesj.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';

function authHeaders(token?: string): Record<string, string> {
  return {
    'apikey': SUPABASE_ANON_KEY,
    'Authorization': `Bearer ${token ?? SUPABASE_ANON_KEY}`,
  };
}

export interface ExcelRow extends Array<any> {}

export interface SyncedRow {
  data: ExcelRow;
  status?: 'pending' | 'synced';
}

export async function getAllSyncedRows(token?: string): Promise<Record<string, SyncedRow>> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products?select=product_id,data,status&order=updated_at.desc`,
      {
        cache: 'no-store',
        headers: authHeaders(token),
      }
    );

    if (!response.ok) {
      const errText = await response.text();
      console.error('getAllSyncedRows failed:', response.status, errText);
      return {};
    }
    const rows = await response.json();
    const result: Record<string, SyncedRow> = {};
    for (const row of rows) {
      result[row.product_id] = { data: row.data, status: row.status };
    }
    return result;
  } catch (error) {
    console.error('Error fetching synced rows from Supabase:', error);
    return {};
  }
}

export async function saveRowToSupabase(articleNo: string, rowData: ExcelRow, token?: string): Promise<{ success: boolean; error?: string }> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...authHeaders(token),
          'Prefer': 'resolution=merge-duplicates',
        },
        body: JSON.stringify({
          product_id: articleNo,
          data: rowData,
          status: 'synced',
          updated_at: new Date().toISOString()
        })
      }
    );

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      return {
        success: false,
        error: `${response.status} ${response.statusText}: ${err.message || err.error_description || 'Unknown error'}`
      };
    }

    return { success: true };
  } catch (error: any) {
    console.error('Error saving to Supabase:', error);
    return { success: false, error: error.message || 'Network error' };
  }
}

export interface HistoryEntry {
  id?: number;
  product_id: string;
  article_name: string;
  old_data: ExcelRow;
  new_data: ExcelRow;
  changed_by: string;
  changed_at: string;
}

export async function saveHistoryEntry(
  productId: string,
  articleName: string,
  oldData: ExcelRow,
  newData: ExcelRow,
  changedBy: string,
  token?: string
): Promise<{ success: boolean; error?: string }> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products_history`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...authHeaders(token),
          'Prefer': 'return=minimal',
        },
        body: JSON.stringify({
          product_id: productId,
          article_name: articleName,
          old_data: oldData,
          new_data: newData,
          changed_by: changedBy,
          changed_at: new Date().toISOString()
        })
      }
    );

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      return {
        success: false,
        error: `History ${response.status}: ${err.message || 'Unknown error'}`
      };
    }

    return { success: true };
  } catch (error: any) {
    console.error('Error saving history to Supabase:', error);
    return { success: false, error: error.message || 'Network error' };
  }
}

export async function getHistory(token?: string): Promise<HistoryEntry[]> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products_history?select=*&order=changed_at.desc&limit=100`,
      {
        cache: 'no-store',
        headers: authHeaders(token),
      }
    );

    if (!response.ok) {
      const err = await response.text();
      return [{
        id: -1,
        product_id: 'ERROR',
        article_name: `Failed: ${response.status} ${err}`,
        old_data: [],
        new_data: [],
        changed_at: new Date().toISOString(),
        changed_by: 'system'
      }];
    }
    return await response.json();
  } catch (error: any) {
    console.error('Error fetching history:', error);
    return [{
      id: -2,
      product_id: 'EXCEPTION',
      article_name: `Message: ${error.message}`,
      old_data: [],
      new_data: [],
      changed_at: new Date().toISOString(),
      changed_by: 'system'
    }];
  }
}

export async function deleteHistoryEntry(id: string, token?: string): Promise<boolean> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products_history?id=eq.${encodeURIComponent(id)}`,
      {
        method: 'DELETE',
        headers: authHeaders(token),
      }
    );

    return response.ok;
  } catch (error) {
    console.error('Error deleting history from Supabase:', error);
    return false;
  }
}

export async function resetAllPendingRows(token?: string): Promise<boolean> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products?status=eq.pending`,
      {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          ...authHeaders(token),
          'Prefer': 'return=minimal',
        },
        body: JSON.stringify({ status: 'synced' })
      }
    );

    return response.ok;
  } catch (error) {
    console.error('Error resetting pending rows in Supabase:', error);
    return false;
  }
}
