"""Mock Platform-2Steps API for testing."""
import json
import secrets
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs


class MockAPIHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        query = parse_qs(parsed.query)

        if path.startswith('/api/v1/categories'):
            # Check if it's a specific category request
            parts = path.split('/')
            if len(parts) == 5 and parts[4].isdigit():
                # GET /api/v1/categories/:id
                category_id = int(parts[4])
                response = {
                    "data": {
                        "id": category_id,
                        "name": f"Category {category_id}",
                        "company_id": 1234,
                        "order": category_id,
                    }
                }
            else:
                # GET /api/v1/categories
                response = {
                    "data": [
                        {"id": 1, "name": "Cortes", "company_id": 1234, "order": 1},
                        {"id": 2, "name": "Coloracion", "company_id": 1234, "order": 2},
                        {"id": 3, "name": "Tratamientos", "company_id": 1234, "order": 3},
                    ],
                    "meta": {"current_page": 1, "total_pages": 1, "total_count": 3}
                }
            self._send_json(200, response)

        elif path.startswith('/api/v1/services'):
            response = {
                "data": [
                    {
                        "id": 1,
                        "name": "Corte de pelo",
                        "service_category_id": 1,
                        "duration": 30,
                        "price": "15000",
                        "active": True,
                    },
                    {
                        "id": 2,
                        "name": "Tintura completa",
                        "service_category_id": 2,
                        "duration": 90,
                        "price": "45000",
                        "active": True,
                    },
                ],
                "meta": {"current_page": 1, "total_pages": 1, "total_count": 2}
            }
            self._send_json(200, response)

        elif path.startswith('/api/v1/bookings'):
            response = {
                "data": [
                    {
                        "id": 101,
                        "service_id": 1,
                        "provider_id": 10,
                        "client_id": 100,
                        "start": "2024-12-15T10:00:00Z",
                        "end": "2024-12-15T10:30:00Z",
                        "status": "confirmed",
                    },
                ],
                "meta": {"current_page": 1, "total_pages": 1, "total_count": 1}
            }
            self._send_json(200, response)

        elif path.startswith('/api/v1/confirmations/'):
            # GET /api/v1/confirmations/:id
            parts = path.split('/')
            confirmation_id = parts[4] if len(parts) > 4 else "unknown"
            response = {
                "confirmation_id": confirmation_id,
                "status": "pending",
                "operation": "create",
                "resource": "category",
                "resource_id": None,
                "preview": {"name": "Test Category"},
                "expires_at": "2024-12-31T23:59:59Z",
                "confirmable": True,
                "result": None,
            }
            self._send_json(200, response)

        else:
            self._send_json(404, {"error": "not_found"})

    def do_POST(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = json.loads(self.rfile.read(content_length)) if content_length else {}

        if self.path.startswith('/api/v1/categories'):
            conf_id = f"conf-{secrets.token_hex(8)}"
            response = {
                "confirmation_id": conf_id,
                "operation": "create",
                "resource": "category",
                "resource_id": None,
                "preview": {"name": body.get('name', 'unnamed')},
                "expires_at": "2024-12-31T23:59:59Z",
                "confirm_url": f"https://plt-2steps.agendapro.com/confirm/{conf_id}",
            }
            self._send_json(202, response)

        elif self.path.startswith('/api/v1/services'):
            conf_id = f"conf-{secrets.token_hex(8)}"
            response = {
                "confirmation_id": conf_id,
                "operation": "create",
                "resource": "service",
                "resource_id": None,
                "preview": {"name": body.get('name', 'unnamed')},
                "expires_at": "2024-12-31T23:59:59Z",
                "confirm_url": f"https://plt-2steps.agendapro.com/confirm/{conf_id}",
            }
            self._send_json(202, response)

        elif self.path.startswith('/api/v1/bookings'):
            conf_id = f"conf-{secrets.token_hex(8)}"
            response = {
                "confirmation_id": conf_id,
                "operation": "create",
                "resource": "booking",
                "resource_id": None,
                "preview": {"service_id": body.get('service_id')},
                "expires_at": "2024-12-31T23:59:59Z",
                "confirm_url": f"https://plt-2steps.agendapro.com/confirm/{conf_id}",
            }
            self._send_json(202, response)

        elif self.path.startswith('/api/v1/batches'):
            operations = body.get('operations', [])
            response = {
                "batch_id": f"batch-{secrets.token_hex(8)}",
                "status": "pending",
                "operations_count": len(operations),
                "expires_at": "2024-12-31T23:59:59Z",
            }
            self._send_json(202, response)

        else:
            self._send_json(404, {"error": "not_found"})

    def do_PUT(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = json.loads(self.rfile.read(content_length)) if content_length else {}

        if self.path.startswith('/api/v1/categories/'):
            parts = self.path.split('/')
            resource_id = int(parts[4]) if len(parts) > 4 else None
            conf_id = f"conf-{secrets.token_hex(8)}"
            response = {
                "confirmation_id": conf_id,
                "operation": "update",
                "resource": "category",
                "resource_id": resource_id,
                "preview": body,
                "expires_at": "2024-12-31T23:59:59Z",
                "confirm_url": f"https://plt-2steps.agendapro.com/confirm/{conf_id}",
            }
            self._send_json(202, response)
        else:
            self._send_json(404, {"error": "not_found"})

    def do_DELETE(self):
        if self.path.startswith('/api/v1/categories/'):
            parts = self.path.split('/')
            resource_id = int(parts[4]) if len(parts) > 4 else None
            conf_id = f"conf-{secrets.token_hex(8)}"
            response = {
                "confirmation_id": conf_id,
                "operation": "delete",
                "resource": "category",
                "resource_id": resource_id,
                "preview": None,
                "expires_at": "2024-12-31T23:59:59Z",
                "confirm_url": f"https://plt-2steps.agendapro.com/confirm/{conf_id}",
            }
            self._send_json(202, response)
        else:
            self._send_json(404, {"error": "not_found"})

    def _send_json(self, status, data):
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def log_message(self, format, *args):
        print(f"[API] {args[0]}")


if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), MockAPIHandler)
    print("Mock Platform-2Steps API running on http://localhost:8000")
    print("Endpoints:")
    print("  GET  /api/v1/categories     - List categories")
    print("  GET  /api/v1/categories/:id - Get category")
    print("  POST /api/v1/categories     - Create category (returns confirmation_id)")
    print("  PUT  /api/v1/categories/:id - Update category (returns confirmation_id)")
    print("  DELETE /api/v1/categories/:id - Delete category (returns confirmation_id)")
    print("  GET  /api/v1/services       - List services")
    print("  POST /api/v1/services       - Create service (returns confirmation_id)")
    print("  GET  /api/v1/bookings       - List bookings")
    print("  POST /api/v1/bookings       - Create booking (returns confirmation_id)")
    print("  POST /api/v1/batches        - Create batch (returns batch_id)")
    print("  GET  /api/v1/confirmations/:id - Get confirmation status")
    server.serve_forever()
