// SPDX-License-Identifier: GPL-3.0-or-later

// Package cli provides the unlock command.
package cli

import (
	"fmt"

	"github.com/spf13/cobra"
)

// UnlockOptions contains options for the unlock command.
type UnlockOptions struct {
	Force bool
}

// newUnlockCommand creates the unlock command.
func (c *CLI) newUnlockCommand() *cobra.Command {
	opts := &UnlockOptions{}

	cmd := &cobra.Command{
		Use:   "unlock",
		Short: "Remove stale repository locks",
		Long: `Remove stale locks from the repository.

Locks are created during operations to prevent concurrent access.
If an operation is interrupted, locks may remain and block future operations.

Only use this if you're sure no other backup operation is running!`,
		Example: `  privatebackup unlock

  # Force unlock without confirmation
  privatebackup unlock --force`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.runUnlock(opts)
		},
	}

	flags := cmd.Flags()
	flags.BoolVar(&opts.Force, "force", false, "Remove all locks without confirmation")

	return cmd
}

// runUnlock executes the unlock command.
func (c *CLI) runUnlock(opts *UnlockOptions) error {
	// Check backend connection
	if err := c.checkBackendConnection(); err != nil {
		if IsBackendNotRunning(err) {
			c.renderer.Error("Cannot connect to backend daemon")
			c.renderer.Info("Start it with: privatebackup daemon start")
			return err
		}
		return fmt.Errorf("backend error: %w", err)
	}

	c.renderer.Info("Checking for stale locks...")
	c.renderer.Newline()

	// In a real implementation, we'd call the backend to:
	// 1. List stale locks
	// 2. Show them to the user
	// 3. Remove them if confirmed

	// Mock: no locks found
	c.renderer.Info("No stale locks found")
	c.renderer.Success("Repository is unlocked")

	// Example of what it would look like with locks:
	/*
		c.renderer.Section("Found 2 stale locks")
		table := output.NewTable(c.renderer)
		table.SetHeader([]string{"Lock ID", "Created"})
		table.AddRow([]string{"abc123", "2 hours ago"})
		table.AddRow([]string{"def456", "1 hour ago"})
		table.Render()
		c.renderer.Newline()

		if !opts.Force {
			confirmed, err := c.prompter.Confirm("Remove locks?", false)
			if err != nil {
				return err
			}
			if !confirmed {
				c.renderer.Info("Operation cancelled")
				return nil
			}
		}

		c.renderer.Success("2 locks removed")
	*/

	return nil
}
