// Gestion des credentials des services git distants (P12). Les secrets (PAT/app password) sont
// chiffrés par SecretBox AVANT insertion et ne ressortent JAMAIS via l'API (résumés sans secret).
// getSecret()/authFor() sont INTERNES (clone, listRepos, test) : jamais routés.
import { randomUUID } from 'node:crypto';
import type {
  CreateGitCredentialRequest,
  GitCredentialSummary,
  GitService,
  TestCredentialResponse,
  UpdateGitCredentialRequest,
} from '@arboretum/shared';
import type { Db } from '../db/index.js';
import type { SecretBox } from './secret-box.js';
import { getGitClient, GitServiceError, type GitAuth } from './git-clients/index.js';
import { recordAudit } from './audit-log.js';

interface GitCredentialRow {
  id: string;
  label: string;
  service: GitService;
  base_url: string | null;
  auth_type: GitCredentialSummary['authType'];
  username: string | null;
  secret_encrypted: string | null;
  ssh_key_path: string | null;
  oauth_access_encrypted: string | null;
  oauth_refresh_encrypted: string | null;
  oauth_expires_at: string | null;
  created_at: string;
  last_tested_at: string | null;
  test_result: string | null;
}

function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
  return Object.assign(new Error(message), { statusCode, code });
}

export class GitCredentialsManager {
  constructor(
    private readonly db: Db,
    private readonly box: SecretBox,
  ) {}

  private getRow(id: string): GitCredentialRow | null {
    return (this.db.prepare('SELECT * FROM git_credentials WHERE id = ?').get(id) as unknown as GitCredentialRow | undefined) ?? null;
  }

  private toSummary(row: GitCredentialRow): GitCredentialSummary {
    let secretLast4: string | null = null;
    if (row.secret_encrypted) {
      try {
        const s = this.box.decrypt(row.secret_encrypted);
        secretLast4 = s.length >= 4 ? s.slice(-4) : '••••';
      } catch {
        secretLast4 = null;
      }
    }
    return {
      id: row.id,
      label: row.label,
      service: row.service,
      baseUrl: row.base_url,
      authType: row.auth_type,
      username: row.username,
      hasSecret: row.secret_encrypted != null,
      secretLast4,
      createdAt: row.created_at,
      lastTestedAt: row.last_tested_at,
      testResult: row.test_result,
    };
  }

  list(): GitCredentialSummary[] {
    const rows = this.db.prepare('SELECT * FROM git_credentials ORDER BY created_at ASC').all() as unknown as GitCredentialRow[];
    return rows.map((r) => this.toSummary(r));
  }

  get(id: string): GitCredentialSummary | null {
    const row = this.getRow(id);
    return row ? this.toSummary(row) : null;
  }

  create(opts: CreateGitCredentialRequest): GitCredentialSummary {
    // P12a : seules les méthodes HTTPS (pat / app_password) sont supportées pour l'instant.
    if (opts.authType !== 'pat' && opts.authType !== 'app_password') {
      throw httpError(400, 'UNSUPPORTED_AUTH', 'Only pat and app_password are supported for now (SSH/OAuth: later phases)');
    }
    if (!opts.label?.trim()) throw httpError(400, 'BAD_REQUEST', 'label is required');
    if (opts.service !== 'gitea' && opts.service !== 'gitlab' && opts.service !== 'github') {
      throw httpError(400, 'BAD_REQUEST', 'service must be gitea, gitlab or github');
    }
    if (opts.service === 'gitea' && !opts.baseUrl) throw httpError(400, 'BAD_REQUEST', 'Gitea requires a base_url');
    if (!opts.secret) throw httpError(400, 'BAD_REQUEST', 'secret (token) is required');
    const row: GitCredentialRow = {
      id: randomUUID(),
      label: opts.label.trim(),
      service: opts.service,
      base_url: opts.baseUrl?.trim() || null,
      auth_type: opts.authType,
      username: opts.username?.trim() || null,
      secret_encrypted: this.box.encrypt(opts.secret),
      ssh_key_path: null,
      oauth_access_encrypted: null,
      oauth_refresh_encrypted: null,
      oauth_expires_at: null,
      created_at: new Date().toISOString(),
      last_tested_at: null,
      test_result: null,
    };
    this.db
      .prepare(
        `INSERT INTO git_credentials (id, label, service, base_url, auth_type, username, secret_encrypted, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      )
      .run(row.id, row.label, row.service, row.base_url, row.auth_type, row.username, row.secret_encrypted, row.created_at);
    return this.toSummary(row);
  }

  update(id: string, patch: UpdateGitCredentialRequest): GitCredentialSummary {
    const row = this.getRow(id);
    if (!row) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
    if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
    if (patch.baseUrl !== undefined) row.base_url = patch.baseUrl.trim() || null;
    if (patch.username !== undefined) row.username = patch.username.trim() || null;
    if (patch.secret) row.secret_encrypted = this.box.encrypt(patch.secret);
    this.db
      .prepare('UPDATE git_credentials SET label = ?, base_url = ?, username = ?, secret_encrypted = ? WHERE id = ?')
      .run(row.label, row.base_url, row.username, row.secret_encrypted, id);
    return this.toSummary(row);
  }

  /** Supprime un credential et NULLifie repos.credential_id (pas de FK). */
  remove(id: string): boolean {
    const res = this.db.prepare('DELETE FROM git_credentials WHERE id = ?').run(id);
    if (res.changes === 0) return false;
    this.db.prepare('UPDATE repos SET credential_id = NULL WHERE credential_id = ?').run(id);
    return true;
  }

  /** Secret déchiffré : INTERNE (clone/listRepos/test). Jamais exposé par une route. */
  getSecret(id: string): string | null {
    const row = this.getRow(id);
    if (!row?.secret_encrypted) return null;
    try {
      return this.box.decrypt(row.secret_encrypted);
    } catch {
      return null;
    }
  }

  /** Contexte d'auth (service, base, secret déchiffré) pour le client API / le clone. */
  authContext(id: string): { service: GitService; baseUrl: string | null; auth: GitAuth } | null {
    const row = this.getRow(id);
    if (!row) return null;
    const secret = this.getSecret(id);
    if (secret == null) return null;
    return { service: row.service, baseUrl: row.base_url, auth: { authType: row.auth_type, username: row.username, secret } };
  }

  /** Teste la connectivité/auth (GET /user) et mémorise le diagnostic. */
  async test(id: string): Promise<TestCredentialResponse> {
    const ctx = this.authContext(id);
    if (!ctx) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
    const now = new Date().toISOString();
    try {
      const { login } = await getGitClient(ctx.service, ctx.baseUrl).verify(ctx.auth);
      this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, 'ok', id);
      return { ok: true, user: login };
    } catch (err) {
      const code = err instanceof GitServiceError ? err.errorCode : 'UNREACHABLE';
      this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, code, id);
      return { ok: false, error: code };
    }
  }
}

/** Helper d'audit partagé (jamais de secret dans details). */
export function auditCredential(db: Db, actor: string, action: string, id: string | null): void {
  recordAudit(db, { actor, action, resourceId: id });
}
