'use strict';

require('../../../universalify/index.js');
var Path = require('path');
require('../fs/index.js');
var index$2 = require('../mkdirs/index.js');
var symlinkPaths$1 = require('./symlink-paths.js');
var symlinkType$1 = require('./symlink-type.js');
var index$3 = require('../path-exists/index.js');
var stat = require('../util/stat.js');
var index = require('../../../../_virtual/index21.js');
var index$1 = require('../../../../_virtual/index20.js');

const u = index.__exports.fromPromise;
const path = Path;
const fs = index$1.__exports;

const { mkdirs, mkdirsSync } = index$2.mkdirs;

const { symlinkPaths, symlinkPathsSync } = symlinkPaths$1.symlinkPaths_1;
const { symlinkType, symlinkTypeSync } = symlinkType$1.symlinkType_1;

const { pathExists } = index$3.pathExists_1;

const { areIdentical } = stat.stat;

async function createSymlink (srcpath, dstpath, type) {
  let stats;
  try {
    stats = await fs.lstat(dstpath);
  } catch { }

  if (stats && stats.isSymbolicLink()) {
    const [srcStat, dstStat] = await Promise.all([
      fs.stat(srcpath),
      fs.stat(dstpath)
    ]);

    if (areIdentical(srcStat, dstStat)) return
  }

  const relative = await symlinkPaths(srcpath, dstpath);
  srcpath = relative.toDst;
  const toType = await symlinkType(relative.toCwd, type);
  const dir = path.dirname(dstpath);

  if (!(await pathExists(dir))) {
    await mkdirs(dir);
  }

  return fs.symlink(srcpath, dstpath, toType)
}

function createSymlinkSync (srcpath, dstpath, type) {
  let stats;
  try {
    stats = fs.lstatSync(dstpath);
  } catch { }
  if (stats && stats.isSymbolicLink()) {
    const srcStat = fs.statSync(srcpath);
    const dstStat = fs.statSync(dstpath);
    if (areIdentical(srcStat, dstStat)) return
  }

  const relative = symlinkPathsSync(srcpath, dstpath);
  srcpath = relative.toDst;
  type = symlinkTypeSync(relative.toCwd, type);
  const dir = path.dirname(dstpath);
  const exists = fs.existsSync(dir);
  if (exists) return fs.symlinkSync(srcpath, dstpath, type)
  mkdirsSync(dir);
  return fs.symlinkSync(srcpath, dstpath, type)
}

var symlink = {
  createSymlink: u(createSymlink),
  createSymlinkSync
};

exports.symlink = symlink;
