import type { ToolModule, ToolDefinition, ToolResult } from './types.js';
import type { GSCClient } from '../lib/gsc-client.js';
import { AddPropertySchema, RemovePropertySchema } from '../schemas/management.js';

/**
 * MANAGEMENT TOOLS
 * Property management operations
 */

// ============================================================================
// ADD PROPERTY
// ============================================================================

const addProperty: ToolDefinition = {
  name: 'add_property',
  description: 'Add a new property to Google Search Console. You must verify ownership before you can access data for this property.',
  category: 'management',
  annotations: {
    readOnlyHint: false,
    idempotentHint: true
  },
  inputSchema: AddPropertySchema,
  _meta: {
    labels: {
      category: "management",
      access: "read",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient): Promise<ToolResult> => {
    try {
      await gscClient.addSite(args.siteUrl);

      let text = `✅ **Property Added Successfully**\n\n`;
      text += `Property: ${args.siteUrl}\n\n`;
      text += `**Important: You must verify ownership before accessing data**\n\n`;
      text += `**Verification methods:**\n`;
      text += `1. **HTML file upload:** Upload a verification file to your site root\n`;
      text += `2. **HTML meta tag:** Add a meta tag to your homepage\n`;
      text += `3. **DNS record:** Add a TXT record to your domain's DNS\n`;
      text += `4. **Google Analytics:** Use your existing GA account\n`;
      text += `5. **Google Tag Manager:** Use your existing GTM container\n\n`;
      text += `Visit the Google Search Console web interface to complete verification:\n`;
      text += `https://search.google.com/search-console\n\n`;
      text += `Once verified, you can use verify_ownership tool to check status.`;

      return {
        content: [{ type: 'text', text }],
        structuredContent: {
          siteUrl: args.siteUrl,
          status: 'added',
          verified: false,
          timestamp: new Date().toISOString(),
          nextSteps: [
            'Visit Google Search Console web interface',
            'Choose a verification method',
            'Complete verification',
            'Check status with verify_ownership tool'
          ]
        }
      };
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);

      // Check if property already exists
      if (errorMsg.includes('already') || errorMsg.includes('exists')) {
        return {
          content: [{
            type: 'text',
            text: `ℹ️ **Property Already Exists**\n\n${args.siteUrl} is already added to your Search Console account.\n\nUse list_properties to see all your properties.`
          }]
        };
      }

      return {
        content: [{
          type: 'text',
          text: `❌ Error adding property: ${errorMsg}\n\n**Common issues:**\n• Invalid property URL format\n• Insufficient permissions\n• Network/API error`
        }],
        isError: true
      };
    }
  }
};

// ============================================================================
// REMOVE PROPERTY
// ============================================================================

const removeProperty: ToolDefinition = {
  name: 'remove_property',
  description: 'Remove a property from Google Search Console. WARNING: This removes the property from your account. Historical data may be lost if no other user has access.',
  category: 'management',
  annotations: {
    readOnlyHint: false,
    destructiveHint: true
  },
  inputSchema: RemovePropertySchema,
  _meta: {
    labels: {
      category: "management",
      access: "delete",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient): Promise<ToolResult> => {
    try {
      await gscClient.removeSite(args.siteUrl);

      let text = `✅ **Property Removed**\n\n`;
      text += `Property: ${args.siteUrl}\n\n`;
      text += `The property has been removed from your Google Search Console account.\n\n`;
      text += `**⚠️ Important notes:**\n`;
      text += `• You no longer have access to this property's data\n`;
      text += `• If no other users have access, historical data may be permanently lost\n`;
      text += `• The property can be re-added later, but it will need to be re-verified\n`;
      text += `• This does NOT affect your site's actual search rankings or indexing\n`;

      return {
        content: [{ type: 'text', text }],
        structuredContent: {
          siteUrl: args.siteUrl,
          status: 'removed',
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);

      // Check if property doesn't exist
      if (errorMsg.includes('not found') || errorMsg.includes('does not exist')) {
        return {
          content: [{
            type: 'text',
            text: `ℹ️ **Property Not Found**\n\n${args.siteUrl} is not in your Search Console account.\n\nUse list_properties to see all your properties.`
          }]
        };
      }

      return {
        content: [{
          type: 'text',
          text: `❌ Error removing property: ${errorMsg}\n\n**Common issues:**\n• Property doesn't exist in your account\n• Insufficient permissions\n• Network/API error`
        }],
        isError: true
      };
    }
  }
};

// ============================================================================
// EXPORTS
// ============================================================================

export const managementTools: ToolModule = {
  tools: [
    addProperty,
    removeProperty
  ]
};
