// #region ProviderConfigIntegrationTest [C:3] [TYPE Module] [SEMANTICS llm, provider-config, integration-test, edit-flow, delete-flow]
// @PURPOSE: Protect edit, submit, test, and delete interaction contracts in LLM provider settings UI.
// @LAYER UI (Tests)
// @RELATION DEPENDS_ON -> [ProviderConfig]
// @INVARIANT: Edit action keeps explicit click handler and opens normalized edit form.
// @INVARIANT: Masked API keys are excluded from save/test/fetch-models payloads.

import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';

const COMPONENT_PATH = path.resolve(
  process.cwd(),
  'src/components/llm/ProviderConfig.svelte',
);

// #region provider_config_edit_contract_tests:Function [TYPE Function]
// @RELATION BINDS_TO -> [EXT:frontend:ProviderConfigIntegrationTest]
// @PURPOSE: Validate edit and delete handler wiring plus normalized edit form state mapping.
// @PRE: ProviderConfig component source exists in expected path.
// @POST: Contract checks ensure edit click cannot degrade into no-op flow.
describe('ProviderConfig edit interaction contract', () => {
  it('keeps explicit edit click handler with guarded button semantics', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain('type="button"');
    expect(source).toContain('onclick={() => handleEdit(provider)}');
  });

  it('normalizes provider payload into editable form shape', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain('formData = {');
    expect(source).toContain('name: provider?.name ?? ""');
    expect(source).toContain('provider_type: provider?.provider_type ?? "openai"');
    expect(source).toContain('default_model: provider?.default_model ?? "gpt-4o"');
    expect(source).toContain('showForm = true;');
  });

  it('preserves masked api_key from provider in edit form', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain('api_key: provider?.api_key ?? ""');
  });

  it('includes isMaskedKey helper to detect masked placeholders', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain('function isMaskedKey(key)');
    expect(source).toContain('key === "********" || key.includes("...")');
  });

  it('excludes masked api_key from fetchModels payload, uses provider_id fallback', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain("if (formData.api_key && !isMaskedKey(formData.api_key))");
    expect(source).toContain('payload.provider_id = editingProvider.id;');
  });

  it('keeps explicit delete flow with confirmation and delete request', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain('async function handleDelete(provider)');
    expect(source).toContain('$t.llm.delete_confirm.replace("{name}", provider.name || provider.id)');
    expect(source).toContain('await requestApi(`/llm/providers/${provider.id}`, "DELETE")');
    expect(source).toContain('onclick={() => handleDelete(provider)}');
  });

  it('excludes masked or empty api_key from submit data when editing', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain("if (editingProvider && (!submitData.api_key || isMaskedKey(submitData.api_key)))");
    expect(source).toContain("delete submitData.api_key;");
  });

  it('excludes masked api_key from test payload when testing connection', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain("if (isMaskedKey(testData.api_key))");
    expect(source).toContain("delete testData.api_key;");
  });

  it('does not forward api_key (masked or otherwise) when toggling provider activation', () => {
    const source = fs.readFileSync(COMPONENT_PATH, 'utf-8');

    expect(source).toContain('const updatePayload = {');
    expect(source).toContain('provider_type: provider.provider_type');
    expect(source).toContain('default_model: provider.default_model');
    expect(source).not.toContain('await requestApi(`/llm/providers/${provider.id}`, "PUT", {\n        ...provider,');
  });
});
// #endregion provider_config_edit_contract_tests:Function
// #endregion ProviderConfigIntegrationTest:Module
