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

export interface ExcelRow extends Array<any> {}

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

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

    if (!response.ok) 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): Promise<boolean> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products?product_id=eq.${encodeURIComponent(articleNo)}`,
      {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'apikey': SUPABASE_KEY,
          'Authorization': `Bearer ${SUPABASE_KEY}`,
          'Prefer': 'return=minimal'
        },
        body: JSON.stringify({
          product_id: articleNo,
          data: rowData,
          status: 'synced',
          updated_at: new Date().toISOString()
        })
      }
    );

    return response.ok;
  } catch (error) {
    console.error('Error saving to Supabase:', error);
    return false;
  }
}

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
): Promise<boolean> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products_history`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'apikey': SUPABASE_KEY,
          'Authorization': `Bearer ${SUPABASE_KEY}`,
          '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()
        })
      }
    );

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

export async function getHistory(): Promise<HistoryEntry[]> {
  try {
    const response = await fetch(
      `${SUPABASE_URL}/rest/v1/products_history?select=*&order=changed_at.desc&limit=100`,
      {
        headers: {
          'apikey': SUPABASE_KEY,
          'Authorization': `Bearer ${SUPABASE_KEY}`
        }
      }
    );

    if (!response.ok) return [];
    return await response.json();
  } catch (error) {
    console.error('Error fetching history from Supabase:', error);
    return [];
  }
}

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

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

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

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