<!-- #region MappingTable [C:3] [TYPE Component] [SEMANTICS mapping, database, editor, crud, migration] -->
<!-- @BRIEF Component component: components/MappingTable.svelte -->
<!-- @LAYER UI -->
<!--
@SEMANTICS: mapping, table, database, editor
@PURPOSE:   Displays and allows editing of database mappings.
@LAYER     Feature
@RELATION  BINDS_TO -> [mappings state]

@INVARIANT: Each source database can be mapped to one target database.
-->

<script lang="ts">
  // [SECTION: IMPORTS]
  import { t } from '$lib/i18n/index.svelte.js';
  // [/SECTION]

  // [SECTION: PROPS]
  let {
    sourceDatabases = [],
    targetDatabases = [],
    mappings = [],
    suggestions = [],
    onupdate = () => {},
  } = $props();

  // [/SECTION]

  // #region updateMapping:Function [TYPE Function]
  /**
   * @purpose Updates a mapping for a specific source database.
   * @pre sourceUuid and targetUuid are provided.
   * @post Parent callback receives normalized mapping payload.
   */
  function updateMapping(sourceUuid: string, targetUuid: string) {
    const sDb = sourceDatabases.find(d => d.uuid === sourceUuid);
    const tDb = targetDatabases.find(d => d.uuid === targetUuid);
    
    onupdate({ 
      sourceUuid, 
      targetUuid,
      sourceName: sDb?.database_name || "",
      targetName: tDb?.database_name || "",
      engine: sDb?.engine || ""
    });
  }
  // #endregion updateMapping:Function

  // #region getSuggestion:Function [TYPE Function]
  /**
   * @purpose Finds a suggestion for a source database.
   * @pre sourceUuid is provided.
   * @post Returns matching suggestion object or undefined.
   */
  function getSuggestion(sourceUuid: string) {
    return suggestions.find(s => s.source_db_uuid === sourceUuid);
  }
  // #endregion getSuggestion:Function
</script>

<!-- [SECTION: TEMPLATE] -->
<div class="overflow-x-auto">
  <table class="min-w-full divide-y divide-gray-200">
    <thead class="bg-gray-50">
      <tr>
        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.dashboard?.source_database }</th>
        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.dashboard?.target_database }</th>
        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.dashboard?.status }</th>
      </tr>
    </thead>
    <tbody class="bg-white divide-y divide-gray-200">
      {#each sourceDatabases as sDb}
        {@const mapping = mappings.find(m => m.source_db_uuid === sDb.uuid)}
        {@const suggestion = getSuggestion(sDb.uuid)}
        <tr class={suggestion && !mapping ? 'bg-green-50' : ''}>
          <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
            {sDb.database_name}
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            <select
              class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
              value={mapping?.target_db_uuid || suggestion?.target_db_uuid || ""}
              onchange={(e) => updateMapping(sDb.uuid, (e.target as HTMLSelectElement).value)}
            >
              <option value="">{$t.migration?.target_env }</option>
              {#each targetDatabases as tDb}
                <option value={tDb.uuid}>{tDb.database_name}</option>
              {/each}
            </select>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            {#if mapping}
              <span class="text-primary font-semibold">{$t.dashboard?.saved }</span>
            {:else if suggestion}
              <span class="text-green-600 font-semibold">{$t.dashboard?.suggested } ({Math.round(suggestion.confidence * 100)}%)</span>
            {:else}
              <span class="text-red-600">{$t.dashboard?.not_mapped }</span>
            {/if}
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
</div>
<!-- [/SECTION] -->


<!-- #endregion MappingTable -->
