package lua_test

import (
	"context"
	"testing"

	"bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/contracts/events"
	luaanalyzer "bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/service/parser/analyzers/lua"
)

const luaSource = `
local json = require("cjson")

local M = {}

function M:handle(request)
  return json.encode(request)
end

local function helper()
  return true
end

M.build = function()
  return {}
end
`

func TestAnalyzerExtractsLuaSymbols(t *testing.T) {
	a := luaanalyzer.NewAnalyzer()
	artifact, chunks, err := a.ParseFile(context.Background(), []byte(luaSource), "scripts/handler.lua", "lua")
	if err != nil {
		t.Fatalf("ParseFile: %v", err)
	}
	if len(chunks) == 0 {
		t.Fatal("expected chunks")
	}

	foundImport := false
	foundTable := false
	foundMethod := false
	foundFunction := false
	for _, node := range artifact.Nodes {
		if node.Name == "cjson" {
			foundImport = true
		}
		if node.Name == "M" && node.Metadata != nil && node.Metadata["type_kind"] == "table" {
			foundTable = true
		}
		if node.Name == "handle" && node.Metadata != nil && node.Metadata["symbol_type"] == string(events.SymbolTypeMethod) {
			foundMethod = true
		}
		if node.Name == "helper" && node.Metadata != nil && node.Metadata["symbol_type"] == string(events.SymbolTypeFunction) {
			foundFunction = true
		}
	}
	if !foundImport {
		t.Fatal("expected require import node")
	}
	if !foundTable {
		t.Fatal("expected module table node")
	}
	if !foundMethod {
		t.Fatal("expected table method node")
	}
	if !foundFunction {
		t.Fatal("expected local function node")
	}
}
