import { z } from 'zod';
import { CompanyDatabase } from '../database/db.js';
import { BrregClient } from '../apis/brreg.js';
const SearchBankruptSchema = z.object({
industry: z.string().optional().describe("NACE-kode for bransje"),
region: z.string().optional().describe("Region/kommune"),
limit: z.number().default(50).describe("Maksimalt antall resultater")
});
/**
* Search specifically for bankrupt companies
* Useful for market analysis, risk assessment, M&A opportunities
*/
export async function searchBankruptCompanies(args: unknown, db: CompanyDatabase, brreg: BrregClient) {
const params = SearchBankruptSchema.parse(args);
console.error('Searching for bankrupt companies:', params);
// Search database first for bankrupt companies
const allCompanies = await db.searchCompanies({
nace_code: params.industry,
municipality: params.region,
exclude_bankrupt: false, // We want bankrupt companies!
limit: params.limit
});
let companies = allCompanies.filter(c => c.bankrupt || c.under_liquidation);
// If few results, fetch from Brønnøysund
if (companies.length < 5) {
console.error('Fetching bankrupt companies from Brønnøysund API...');
const brregResults = await brreg.searchBankruptCompanies(params.industry, params.limit);
for (const company of brregResults) {
await db.insertOrUpdateCompany({
org_nr: company.organisasjonsnummer,
name: company.navn,
organization_form: company.organisasjonsform?.beskrivelse,
organization_form_code: company.organisasjonsform?.kode,
nace_code: company.naeringskode1?.kode,
nace_description: company.naeringskode1?.beskrivelse,
employees_count: company.antallAnsatte,
established_date: company.registreringsdatoEnhetsregisteret,
business_address: company.forretningsadresse?.adresse?.join(', '),
business_postcode: company.forretningsadresse?.postnummer,
business_city: company.forretningsadresse?.poststed,
business_municipality: company.forretningsadresse?.kommune,
business_municipality_number: company.forretningsadresse?.kommunenummer,
in_mva_register: company.registrertIMvaregisteret,
in_foretaksregister: company.registrertIForetaksregisteret,
bankrupt: company.konkurs,
under_liquidation: company.underAvvikling,
under_forced_liquidation: company.underTvangsavviklingEllerTvangsopplosning,
last_updated: new Date().toISOString()
});
}
// Re-query database
const refreshedCompanies = await db.searchCompanies({
nace_code: params.industry,
municipality: params.region,
exclude_bankrupt: false,
limit: params.limit
});
companies = refreshedCompanies.filter(c => c.bankrupt || c.under_liquidation);
// If still no results, return API results directly
if (companies.length === 0 && brregResults.length > 0) {
companies = brregResults.map(c => ({
org_nr: c.organisasjonsnummer,
name: c.navn,
organization_form: c.organisasjonsform?.beskrivelse,
nace_code: c.naeringskode1?.kode,
nace_description: c.naeringskode1?.beskrivelse,
employees_count: c.antallAnsatte,
business_city: c.forretningsadresse?.poststed,
business_municipality: c.forretningsadresse?.kommune,
bankrupt: c.konkurs,
under_liquidation: c.underAvvikling
})).slice(0, params.limit);
}
}
if (companies.length === 0) {
return {
content: [{
type: "text" as const,
text: `Ingen konkursrammede selskaper funnet${params.industry ? ` i NACE ${params.industry}` : ''}${params.region ? ` i ${params.region}` : ''}.`
}]
};
}
const formatted = companies.map((c, idx) => {
const status = [];
if (c.bankrupt) status.push('🔴 KONKURS');
if (c.under_liquidation) status.push('⚠️ AVVIKLING');
return `${idx + 1}. **${c.name}**
📍 ${c.business_city || 'Ukjent'}, ${c.business_municipality || ''}
🏢 ${c.organization_form || 'Ukjent'}
🏷️ NACE: ${c.nace_code || 'Ukjent'} - ${c.nace_description || ''}
📋 Org.nr: ${c.org_nr}
${status.join(' ')}`;
}).join('\n\n');
return {
content: [{
type: "text" as const,
text: `🔴 KONKURSRAMMEDE SELSKAPER
Fant ${companies.length} selskaper i konkurs eller avvikling:
${params.industry ? `\n🏷️ Bransje: NACE ${params.industry}` : ''}
${params.region ? `\n📍 Region: ${params.region}` : ''}
${formatted}
💡 BRUK:
- Identifiser konkurrenter i trøbbel
- Finn potensielle oppkjøpsmuligheter (asset deals)
- Analyser konkursmønstre i bransjen
- Vurder markedsrisiko
`
}]
};
}