import { PrismaMariaDb } from '@prisma/adapter-mariadb';
import { PrismaClient } from '../generated/prisma/client.js';

export function mysqlConnectionOptions(connectionString: string) {
  const url = new URL(connectionString);
  if (url.protocol !== 'mysql:' || !url.hostname || !/^\/[A-Za-z0-9_]+$/.test(url.pathname)) {
    throw new Error('Use a mysql:// URL with a host and database name containing only letters, digits, or underscores.');
  }
  for (const key of url.searchParams.keys()) {
    if (key !== 'sslaccept') throw new Error(`Unsupported MySQL URL parameter: ${key}`);
  }
  const sslaccept = url.searchParams.get('sslaccept');
  if (sslaccept !== null && sslaccept !== 'strict') throw new Error('Only sslaccept=strict is supported.');
  return {
    host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 3306),
    user: decodeURIComponent(url.username), password: decodeURIComponent(url.password),
    database: url.pathname.slice(1), timezone: '+00:00',
    // MySQL 8.4 uses caching_sha2_password. Local TCP may retrieve the server's
    // RSA key; use verified TLS for remote connections (sslaccept=strict).
    allowPublicKeyRetrieval: !sslaccept && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname),
    connectionLimit: 10, ...(sslaccept ? { ssl: { rejectUnauthorized: true } } : {}),
  };
}

export function createPrismaClient(connectionString: string) {
  return new PrismaClient({ adapter: new PrismaMariaDb(mysqlConnectionOptions(connectionString)) });
}
