// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

import { UsageError } from '../../../errors.ts'
import { extraOperandError } from '../../../spec/usage.ts'
import { IOResult } from '../../../../io/types.ts'
import { FileType } from '../../../../types.ts'
import { type Builder, resolveGlobOf } from '../adapter.ts'

export const UNLINK_BUILDER: Builder = {
  name: 'unlink',
  write: true,
  requirements: ['unlink'],
  fn: async (ops, accessor, paths, _texts, opts) => {
    if (paths.length === 0) {
      throw new UsageError("unlink: missing operand\nTry 'unlink --help' for more information.", 1)
    }
    const idx = opts.index ?? undefined
    const resolved = await resolveGlobOf(ops)(accessor, paths, idx)
    if (resolved.length > 1) {
      const extra = resolved[1]
      throw extraOperandError('unlink', extra === undefined ? '' : extra.rawPath)
    }
    const p = resolved[0]
    if (p === undefined) return [null, new IOResult()]
    const { unlink } = ops
    if (unlink === undefined) {
      throw new Error('unlink: remove not supported on this backend')
    }
    const enc = new TextEncoder()
    const links = opts.ns?.links ?? null
    // unlink(2) never follows, so a trailing slash on a link operand is
    // refused rather than resolved: GNU answers `unlink dlink/` and
    // `unlink flink/` alike with ENOTDIR, where a real directory under a
    // slash is EISDIR. A bare link operand never reaches here at all --
    // the dispatcher removes the link entry, which no backend can see.
    if (links !== null && p.rawPath.endsWith('/') && links.statAt(p.virtual) !== null) {
      return [
        null,
        new IOResult({
          exitCode: 1,
          stderr: enc.encode(`unlink: cannot unlink '${p.rawPath}': Not a directory\n`),
        }),
      ]
    }
    let isDir = false
    try {
      const st = await ops.stat(accessor, p, idx)
      isDir = st.type === FileType.DIRECTORY
    } catch (err) {
      const detail =
        (err as { code?: string }).code === 'ENOTDIR'
          ? 'Not a directory'
          : 'No such file or directory'
      return [
        null,
        new IOResult({
          exitCode: 1,
          stderr: enc.encode(`unlink: cannot unlink '${p.rawPath}': ${detail}\n`),
        }),
      ]
    }
    if (isDir) {
      return [
        null,
        new IOResult({
          exitCode: 1,
          stderr: enc.encode(`unlink: cannot unlink '${p.rawPath}': Is a directory\n`),
        }),
      ]
    }
    await unlink(accessor, p)
    return [null, new IOResult()]
  },
}
