import type { Customer } from '../billing/middleware.js';
import type { OAuthCredentials } from '../multitenancy/credential-store.js';
import { createToolAudit } from '../multitenancy/audit-log.js';

const LINKEDIN_API_BASE = 'https://api.linkedin.com/v2';

function getEnvToken(account: string): string {
  const envKey = `LINKEDIN_${account.toUpperCase()}_ACCESS_TOKEN`;
  return process.env[envKey] ?? '';
}

async function resolveToken(args: { account?: string }, customer?: Customer): Promise<string> {
  if (customer) {
    const creds = await customer.getCredential<OAuthCredentials>('linkedin');
    if (!creds) throw new Error('LinkedIn not connected for this account');
    return creds.accessToken;
  }
  const token = getEnvToken(args.account ?? 'default');
  if (!token) throw new Error('Missing LinkedIn credentials. Set LINKEDIN_{ACCOUNT}_ACCESS_TOKEN');
  return token;
}

async function linkedinRequest(
  endpoint: string,
  accessToken: string,
  method: 'GET' | 'POST' = 'GET',
  body?: unknown
) {
  const url = `${LINKEDIN_API_BASE}${endpoint}`;
  const res = await fetch(url, {
    method,
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json',
      'X-Restli-Protocol-Version': '2.0.0',
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(15000),
  });

  if (!res.ok) {
    const error = await res.text();
    throw new Error(`LinkedIn API error (${res.status}): ${error}`);
  }

  return res.json();
}

export async function getProfile(
  args: { account?: string },
  customer?: Customer
): Promise<{
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  picture?: string;
}> {
  const accessToken = await resolveToken(args, customer);

  const res = await fetch(`${LINKEDIN_API_BASE}/userinfo`, {
    headers: { 'Authorization': `Bearer ${accessToken}` },
    signal: AbortSignal.timeout(15000),
  });

  if (!res.ok) {
    const error = await res.text();
    throw new Error(`LinkedIn API error (${res.status}): ${error}`);
  }

  const data = await res.json();
  return {
    id: data.sub,
    firstName: data.given_name ?? '',
    lastName: data.family_name ?? '',
    email: data.email ?? '',
    picture: data.picture ?? '',
  };
}

export async function createPost(
  args: { text: string; visibility?: 'PUBLIC' | 'CONNECTIONS'; account?: string },
  customer?: Customer
): Promise<{ success: boolean; post_id: string; url: string }> {
  const audit = customer ? createToolAudit(customer.id, 'linkedin:createPost') : null;
  const auditArgs = { text: args.text.slice(0, 100) };
  const accessToken = await resolveToken(args, customer);

  const profile = await getProfile(args, customer);
  const authorUrn = `urn:li:person:${profile.id}`;

  const body = {
    author: authorUrn,
    lifecycleState: 'PUBLISHED',
    specificContent: {
      'com.linkedin.ugc.ShareContent': {
        shareCommentary: { text: args.text },
        shareMediaCategory: 'NONE',
      },
    },
    visibility: {
      'com.linkedin.ugc.MemberNetworkVisibility': args.visibility ?? 'PUBLIC',
    },
  };

  try {
    const data = await linkedinRequest('/ugcPosts', accessToken, 'POST', body);
    const postId = data.id ?? '';
    const result = {
      success: true,
      post_id: postId,
      url: postId ? `https://www.linkedin.com/feed/update/${postId}` : '',
    };
    if (audit) await audit.success(auditArgs);
    return result;
  } catch (err) {
    if (audit) await audit.error(auditArgs, String(err));
    throw err;
  }
}

export async function searchConnections(
  args: { keywords?: string; account?: string },
  _customer?: Customer
): Promise<{ message: string }> {
  throw new Error(
    'LinkedIn connections search requires the LinkedIn Partnership Program. ' +
    'Public API access to connections was removed. ' +
    'Apply at https://developer.linkedin.com/partner-programs'
  );
}

export async function sendMessage(
  args: { recipient_id: string; message: string; account?: string },
  _customer?: Customer
): Promise<{ message: string }> {
  throw new Error(
    'LinkedIn messaging requires the LinkedIn Partnership Program. ' +
    'Direct messaging is not available through the public API. ' +
    'Apply at https://developer.linkedin.com/partner-programs'
  );
}
