import { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts'
import { EC2Client, DescribeInstancesCommand } from '@aws-sdk/client-ec2'
import type { IntegrationAdapter, Resource } from './types.js'

function credentialsFrom(secrets: Record<string, string>, config: Record<string, string>) {
  return {
    region: config.region || 'us-east-1',
    credentials: {
      accessKeyId: secrets.accessKey ?? config.accessKey,
      secretAccessKey: secrets.secretKey,
    },
  }
}

export const aws: IntegrationAdapter = {
  async testConnection(config, secrets) {
    if (!config.accessKey && !secrets.accessKey) return { ok: false, message: 'Missing access key' }
    if (!secrets.secretKey) return { ok: false, message: 'Missing secret key' }
    try {
      const client = new STSClient(credentialsFrom(secrets, config))
      const identity = await client.send(new GetCallerIdentityCommand({}))
      return { ok: true, message: `Connected as ${identity.Arn}` }
    } catch (err) {
      return { ok: false, message: err instanceof Error ? err.message : 'Connection failed' }
    }
  },

  async listResources(config, secrets): Promise<Resource[]> {
    if (!secrets.secretKey || !(config.accessKey || secrets.accessKey)) return []
    try {
      const client = new EC2Client(credentialsFrom(secrets, config))
      const result = await client.send(new DescribeInstancesCommand({}))
      const resources: Resource[] = []
      for (const reservation of result.Reservations ?? []) {
        for (const instance of reservation.Instances ?? []) {
          const nameTag = instance.Tags?.find((t) => t.Key === 'Name')?.Value
          const state = instance.State?.Name
          resources.push({
            name: nameTag || instance.InstanceId || 'unknown',
            status: state === 'running' ? 'healthy' : state === 'stopped' || state === 'terminated' ? 'critical' : 'warning',
            detail: `${instance.InstanceType ?? 'unknown type'} — ${state}`,
          })
        }
      }
      return resources
    } catch {
      return []
    }
  },
}
